为什么 2 个双精度值之间的差值计算错误?

Why is the difference between 2 double values wrongly calculated?

本文关键字:计算 错误 之间 双精度 为什么      更新时间:2023-10-16

我需要仅通过第一个精度来计算 2 个字符串数字之间的差异值。我必须先转换为双倍,然后计算差值,如下所示

#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.但是这个程序返回这个值:

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 本身不是一个可表示的数字,因此无论您的输入是什么,都无法将其作为浮点运算的结果。


如何正确获得我想要的值?

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

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

只要计算误差不超过所需精度的一半,这就可以工作。

如果您不想处理计算中的任何精度错误,则不得使用浮点数。

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

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