Floating point comparison `a! = 0.7`

Possible duplicate:
floating point comparison problems

#include <stdio.h> #include <conio.h> main() { float a = 0.7; if(a < 0.7) printf("C"); else printf("C++"); } 

In the above code, the output signal is C I tried this code in Code :: Blocks and Pelles C but got the same answer. I would like to know the reason for this in detail!

+4
source share
3 answers

In binary terms, 0.7:

 b0.1011001100110011001100110011001100110011001100110011001100110... 

However, 0.7 is a double precision literal whose value is 0.7, rounded to the nearest represented double precision value, which is:

 b0.10110011001100110011001100110011001100110011001100110 

In decimal, this is for sure:

  0.6999999999999999555910790149937383830547332763671875 

When you write float a = 0.7 , this double value is again rounded to one precision, and a gets a binary value:

 b0.101100110011001100110011 

which is exactly equal

  0.699999988079071044921875 

in decimal form.

When you perform a comparison (a < 0.7) , you compare this value of one precision (converted to double, which does not round, since all values ​​with the same precision are represented in double precision) to the original value of double precision. Because the

  0.699999988079071044921875 < 0.6999999999999999555910790149937383830547332763671875 

the comparison returns true correctly, and your program prints "C" .

Please note that none of this is different from the C ++ language, and the appearance of the code in question is vice versa. There are certain (numerically dangerous) compiler optimizers that can change behavior, but they are not unique to C or C ++.

+19
source

This is because 0.7 is of type double , therefore a converted to double , and comparisons are made in this type. Since 0.7 does not appear exactly in binary floating point, you get some rounding error and the comparison becomes true.

You can:

 if( a < 0.7f ) { .... 

But in fact, this effect is also true for C ++, so your conditional code is not quite right.

+8
source

Bart gave a very good link in his comment, but I would also recommend this very simple rule:

Not all numbers can be represented exactly on the computer, therefore, as soon as you use floating point numbers (for example, float and double), you should expect that there will be a small unpredictable error in each saved number. No, this is not accidental or unpredictable, but until you learn more about it, you can consider it unpredictable. Therefore, matching, such as your a <0.7 , may turn out to be true, and it may not be. Do not write code that depends on it.

+3
source

All Articles