Is binary equality comparison of floats correct?

  • A+

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?


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 ==:

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

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: