繁体   English   中英

为什么将浮点表示与精度结合起来不起作用?

[英]Why combining floating point representation with precision is not working?

为什么下面的代码在要求精度之前没有给出正确的 output? 请注意,因为我使用的是 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; 
}

产生 output 作为

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

为什么 output 不是

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

我期待 output 数字与输入数字匹配,直到达到要求的精度,但事实并非如此。 为什么这样?

d3没有 OP 期望的值。


double通常是 64 位 object,因此可以准确表示大约 2 64 个不同的值。

50388143.0682372156805328369140625不是其中之一。

典型的double编码为 integer(小于 2 53 )乘以 2 的某个幂。请参阅dyadic rational

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

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

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

50388143.06823721528053284

如OP所见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM