Is binary equality comparison of floats correct?

Viewed 3301

I'm working on different memory block manipulation functions and during benchmarks I noticed, that my implementation of the IsEqualRange(double* begin1, double* end1, double* begin2, double* end2) is much faster then the std::equals(...) on MSVC and GCC as well. Further investigation showed, that doubles and floats are not block compared by memcmp, but in a for loop one by one.

In what situation does binary comparison of floats lead to incorrect result? When is it ok to binary compare (equality) array of floats/doubles? Are there other fundamental types where I shouldn't use memcmp?

3 Answers

The first thing I would do if I were you is to check your optimisation settings.

It's fine to use memcmp for an array of floating points but note that you could get different results to element-by-element ==. In particular, for IEEE754 floating point:

  1. +0.0 is defined to compare equal to -0.0.

  2. NaN is defined to compare not-equal to NaN.

The main issue is nan values, as these are never equal to themselves. There is also two representations of 0 (+0 and -0) that are equal but not binary equal.

So strictly speaking, you cannot use memcmp for them, as the answer would be mathematically incorrect.

If you know that you don't have nan or 0 values, then you can use memcmp.

Binary compare works with too much precision for many actual applications. For example, in javascript, 0.2 / 10.0 != 0.1 * 0.2 If you have two variables that both end up with very, very slight rounding errors, they will be unequal despite representing the "same" number.

Related