简体   繁体   English

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

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

WHy is below code not giving proper output till requested precision?为什么下面的代码在要求精度之前没有给出正确的 output? Please note that since i am using std::fixed so i am expecting precision to be representing digits after decimal points.请注意,因为我使用的是 std::fixed 所以我期望精度代表小数点后的数字。 Hope thats correct?希望那是正确的?

#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; 
}

Produces output as产生 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

Why isn't the output coming as为什么 output 不是

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

I was expecting the output digits to match with input digits till requested precision but its not the case.我期待 output 数字与输入数字匹配,直到达到要求的精度,但事实并非如此。 Why so?为什么这样?

d3 does not have the value OP expects. d3没有 OP 期望的值。


double is typically a 64-bit object and so can exactly represent about 2 64 different values. double通常是 64 位 object,因此可以准确表示大约 2 64 个不同的值。

50388143.0682372156805328369140625 is not one of them. 50388143.0682372156805328369140625不是其中之一。

Typical double is encoded as an integer (less than 2 53 ) times some power of 2. See dyadic rational .典型的double编码为 integer(小于 2 53 )乘以 2 的某个幂。请参阅dyadic rational

The closest double is 1690745520189437 * pow(2,-25) or最接近的double1690745520189437 * pow(2,-25)

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

Printing 50388143.068237215_2802805328369140625 with setprecision(17) is expected to be:使用 setprecision setprecision(17)打印50388143.068237215_2802805328369140625预计为:

50388143.06823721528053284

as seen by OP.如OP所见。

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

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