The C++ FAQ lite "[29.17] Why doesn't my floating-point comparison work?" recommends this equality test:
#include <cmath> /* for std::abs(double) */
inline bool isEqual(double x, double y)
{
const double epsilon = /* some small number such as 1e-5 */;
return std::abs(x - y) <= epsilon * std::abs(x);
// see Knuth section 4.2.2 pages 217-218
}
+0
and -0
?|x| < epsilon
?Update
As pointed out by Daniel Daranas the function should probably better be called isNearlyEqual
(which is the case I care about).
有人指出了"Comparing Floating Point Numbers",我想更突出地分享它。