为什么结合浮点表示与精度不工作?



为什么下面的代码没有给出正确的输出,直到要求的精度?请注意,由于我使用std::fixed,所以我期望精度表示小数点后的数字。希望这是正确的?

#include <iostream>
#include <limits>
#include <cmath>
#include <iomanip>
int main()
{
double d3 = 50388143.0682372156805328369140625;
std::cout << "d3 = " << d3 << std::endl; 
std::cout << std::setprecision(17) << std::fixed << "d3 = " << d3 << std::endl; 
std::cout << std::setprecision(20) << std::fixed << "d3 = " << d3 << std::endl; 
}

输出

d3 = 5.03881e+07
d3 = 50388143.06823721528053284   // See its different than original floating point
d3 = 50388143.06823721528053283691 // See its different than original floating point

为什么输出不是

d3 = 5.03881e+07
d3 = 50388143.06823721568053283
d3 = 50388143.06823721568053283691

我期望输出数字与输入数字匹配,直到要求精度,但事实并非如此。为什么如此?

d3没有OP期望的值


double是典型的64位对象,因此可以准确地表示大约264不同的值。

50388143.0682372156805328369140625 isnot其中之一。

典型的double被编码为整数(小于253)乘以2的某个幂。

最接近的double1690745520189437 * pow(2,-25)

50388143.068237215_2805328369140625   // closest double
50388143.068237215_6805328369140625   // OP's original code.
50388143.068237222_731113433837890625 // next best double

setprecision(17)打印50388143.068237215_2802805328369140625预计为:

50388143.06823721528053284
OP.

最新更新