您的位置:首页 > 编程语言 > C语言/C++

C/C++ 浮点数比较问题

2015-12-10 22:11 363 查看
本系列文章由 @YhL_Leo 出品,转载请注明出处。

文章链接: http://blog.csdn.net/yhl_leo/article/details/50255623


Never try to check two floating point variables for equality



C/C++ 浮点数比较是否相等时,有些细节必须要意识到,,例如下面的代码:

#include <iostream>

using namespace std;

void main()
{
double epsilon=0.001;
double d1=2.334;
double d2=2.335;

cout << "epsilon is: " << epsilon << endl;
cout << "d2-d1 is: " << d2-d1 << endl;

if ((d2 - d1) == epsilon){
cout << "Equal!" << endl;
}
else{
cout << "Not equal!" << endl;
}
}


其输出结果实际上是:

epsilon is: 0.001
d2-d1 is: 0.001
Not equal!


为何会这样呢?让我们稍微调整一下上面的代码:

cout<<"epsilon is: "<< setprecision(20) << epsilon<<endl;
cout<<"d2-d1   is: "<< setprecision(20) << d2-d1 <<endl;


可以得到:

epsilon is: 0.00100000000000000000
d2-d1 is: 0.00099999999999988987


这里引出一条C/C++中非常重要的原则:


The important rule to remember is that powers of two and integer multiples thereof can be perfectly represented. everything else is an approximation.



直译过来意识就是,除了可以表示为2的幂次以及整数数乘的浮点数可以准确表示外,其余的数的值都是近似值。

例如,
1.5
可以精确表示,因为
1.5 = 3*2^(-1)
;然而
3.6
却不能精确表示,因为它并不满足这一规则。

此处的例子程序里,这里如果想要判断这样两个浮点数,是否相等,采用
==
结果就会看似出乎意料,可以调整为:

if(abs(d2 - d1) < epsilon)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: