Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 899
Wizmann Avatar asked May 06 '15 03:05

Wizmann


3 Answers

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
like image 165
Nayuki Avatar answered Oct 16 '22 16:10

Nayuki


gcc and clang use the UCOMISS x86/x64 instruction.

Source: tried it with -O3 and inspected the assembly output.

like image 34
M.M Avatar answered Oct 16 '22 16:10

M.M


I'm assuming you mean after the program is compiled, how does it compare two floats. The way floats are stored is very unique. It is stored by sign, exponent and fraction as seen here. Therefore, unless it is absolutly equal, the program will see even 1 and 1.000000000001 as different. To check if they are almost equal, you can use the following:

bool AlmostEqualRelativeOrAbsolute(float A, float B,
            float maxRelativeError, float maxAbsoluteError)
{
    if (fabs(A - B) < maxAbsoluteError)
        return true;
    float relativeError;
    if (fabs(B) > fabs(A))
        relativeError = fabs((A - B) / B);
    else
        relativeError = fabs((A - B) / A);
    if (relativeError <= maxRelativeError)
        return true;
    return false;
}

The code is obtained from here, you may want to read more at the site.

like image 1
Ivan Ling Avatar answered Oct 16 '22 16:10

Ivan Ling