Search code examples
c++cfloating-point-precision

How do C and C++ compilers implement the decision of equality for float numbers?


For example,

float a = 1.0;
float b = 1.2;

puts(a == b? "equal": "not equal");

Does compiler deal with it bitwisely or by some other methods?

(I know it's not a good choice to decide the equality of floating-point numbers by "==", I just want to know how a compiler deals with this situation.)


Solution

  • The general, full answer is that floating-point numbers are compared according to the IEEE 754 specification.

    To answer your question specifically, most of the time two floating-point numbers are compared bitwise, with a few exceptional cases:

    • Positive and negative zero are considered equal
    • NaN is considered unequal to everything, even to NaN itself
    • Subnormals may compare equal to zero and other subnormals in certain operating modes (e.g. "flush subnormals to zero")
    • Other than these exceptions, regular bitwise comparison is used