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.)
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:
gcc and clang use the UCOMISS x86/x64 instruction.
Source: tried it with -O3
and inspected the assembly output.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With