How do C and C ++ compilers implement an equality solution for floating point numbers?

For example,

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

Is the compiler combined with it or some other way?

(I know that it’s nice to choose the equality of floating-point numbers to "==", I just want to know how the compiler deals with this situation.)

+7
c ++ c floating-point-precision
source share
3 answers

The general complete 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 NaN itself
  • Subnormal values ​​can be compared with zero and other subnormal values ​​in certain operating modes (for example, “attenuation of subnormal values ​​to zero”)
  • In addition to these exceptions, the usual bitwise comparison is used.
+5
source share

gcc and clang use the UCOMISS x86 / x64 instruction.

Source: tried it with -O3 and checked the build output.

+3
source share

I assume that you mean when a program is compiled, how it compares two floats. The float storage method is very unique. It is stored by sign, exponent and fraction, as shown here . Therefore, if it is not absolutely equal, the program will see even 1 and 1.000000000001 as different. To make sure 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 can find out more on the site.

+1
source share

All Articles