Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point comparison [duplicate]

int main() {     float a = 0.7;     float b = 0.5;     if (a < 0.7)     {        if (b < 0.5) printf("2 are right");        else         printf("1 is right");     }     else printf("0 are right"); } 

I would have expected the output of this code to be 0 are right. But to my dismay the output is 1 is right why?

like image 351
sasidhar Avatar asked Aug 10 '11 13:08

sasidhar


People also ask

What is a better way to compare floating point values?

To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Can we compare double with float?

Float has to round more than double, because it is smaller, so 1.1 rounded to the nearest valid Float is different to 1.1 rounded to the nearest valud Double.

Why do we never use == to compare floating point numbers?

Because floating point arithmetic is different from real number arithmetic. Bottom line: Never use == to compare two floating point numbers. Here's a simple example: double x = 1.0 / 10.0; double y = x * 10.0; if (y !=

Are Doubles more precise than float?

double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.


1 Answers

int main() {     float a = 0.7, b = 0.5; // These are FLOATS     if(a < .7)              // This is a DOUBLE     {       if(b < .5)            // This is a DOUBLE         printf("2 are right");       else         printf("1 is right");     }     else       printf("0 are right"); } 

Floats get promoted to doubles during comparison, and since floats are less precise than doubles, 0.7 as float is not the same as 0.7 as double. In this case, 0.7 as float becomes inferior to 0.7 as double when it gets promoted. And as Christian said, 0.5 being a power of 2 is always represented exactly, so the test works as expected: 0.5 < 0.5 is false.

So either:

  • Change float to double, or:
  • Change .7 and .5 to .7f and .5f,

and you will get the expected behavior.

like image 81
user703016 Avatar answered Sep 20 '22 19:09

user703016