为什么错误计算了 2 个 double 值之间的差异?

Why is the difference between 2 double values wrongly calculated?

我需要只取第一个精度来计算两个字符串数字之间的差值。我必须先转换为 double 然后计算差异如下

#include <iostream>
#include <math.h>
#include <string>

using namespace std;

int main()
{
    string v1 = "1568678435.244555";
    string v2 = "1568678435.300111";

    double s1 = atof(v1.substr(0,12).c_str());  // take upto first precision and convert to double
    double s2 = atof(v2.substr(0,12).c_str());  // take upto first precision and convert to double
    std::cout<<s1<<" "<<s2<<" "<<s2-s1<<endl;
    if (s2-s1 >= 0.1)
        cout<<"bigger";
    else
        cout<<"smaller";

    return 0;
}

我预计计算结果为 1568678435.3 - 1568678435.2 = 0.1。但是这个程序returns这个值:

1.56868e+09 1.56868e+09 0.0999999                                                                               
smaller

这是为什么以及如何正确获得我想要的值?

浮点格式的精度有限。并非所有值都可以表示。例如,数字 1568678435.2 不可表示(采用 IEEE-754 二进制 64 格式)。最接近的可表示值是:

1568678435.2000000476837158203125

1568678435.3 也不是可表示的值。最接近的可表示值是:

1568678435.2999999523162841796875

鉴于您开始时使用的浮点值不精确,因此计算结果也不精确也就不足为奇了。这些数相减的浮点数结果为:

0.099999904632568359375

非常接近 0.1,但不完全是。计算错误为:

0.000000095367431640625

另请注意,0.1 本身不是可表示的数字,因此无论您的输入是什么,都无法将其作为浮点运算的结果。


how to get the value that I want properly?

要打印值 0.1,只需将输出四舍五入到足够粗的精度即可:

std::cout << std::fixed << std::setprecision(1) << s2-s1;

只要计算误差不超过所需精度的一半,此方法就有效。

如果您不想在计算中处理任何精度错误,那么您一定不要使用浮点数。

您应该四舍五入这些值之间的差异。

if (round((s2-s1) * 10) >= 1)
    cout<<"bigger";
else
    cout<<"smaller";