C ++漂浮点问题 [英] C++ Floating point gotcha
问题描述
可能重复:
最有效的方法进行浮点数和双比较
我是C ++新手。我有一个疑问,而阅读C ++。
如何决定两个浮点数相等或不相等?
显然,你不应该使用 operator ==
来比较它们。
这里的重要概念是,如果两个浮点数的差别足够小,足以解决问题的精度要求比你的误差范围,我们应该认为他们是平等的。
有一些实用的方法建议,比如
fabs(f1 - f2)精度要求
fabs(f1-f2)< max(fabs(f1),fabs(f2))*百分比精度要求
Possible Duplicate:
Most effective way for float and double comparison
I am new to C++. I had a doubt, while reading C++. How to decide two floating point numbers equal to each other or not ?
Thanks in advance
Obviously, you should not use operator ==
to compare them.
The important concept here is if the difference of your two floating point number is small enough to the precision requirement of your problem to solve or smaller than your error range, we should consider them as equal.
There are some practical methods suggestions such as
fabs(f1 - f2) < precision-requirement
fabs(f1 - f2) < max(fabs(f1), fabs(f2)) * percentage-precision-requirement
这篇关于C ++漂浮点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!