且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++漂浮点问题

更新时间:2022-10-15 09:19:33

显然,你不应该使用 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