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++ 浮点数比较是否相等时,有些细节必须要意识到,,例如下面的代码:
其输出结果实际上是:
为何会这样呢?让我们稍微调整一下上面的代码:
可以得到:
这里引出一条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的幂次以及整数数乘的浮点数可以准确表示外,其余的数的值都是近似值。
例如,
此处的例子程序里,这里如果想要判断这样两个浮点数,是否相等,采用
文章链接: 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)
相关文章推荐
- C/C++ 浮点数比较问题
- C/C++ Swap without using extra variable
- C/C++ Swap without using extra variable
- C++面试1(简答题)
- 实战c++中的string系列--string的替换、查找(一些与路径相关的操作)
- 实战c++中的string系列--string的替换、查找(一些与路径相关的操作)
- c语言—stdarg宏(函数可变参数实现)
- 【日记-C语言】今天看书,吸LFG
- c++实训报告之高校工资管理系统
- Arduino 平台与C语言程序设计-week4-Arduino Programs-Lesson1
- C/C++ Quick Sort Algorithm
- C/C++ Quick Sort Algorithm
- c++设计模式(4)------建造者模式
- 一起talk C栗子吧(第七十三回:C语言实例--DIY pwd命令)
- c语言指针
- C++中的萃取机制(traits)
- 对象池 c++11
- 条款01:视C++为一个语言联邦
- c++实现 斐波那契数
- 浅谈C++友元