Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greater than lesser than comparison in floating points in C [duplicate]

Tags:

c

Consider the following code:

float x = 0.1;
if ( x> 0.1){
    printf("if");
}

Now when I check equality, it is explained that x is being converted to double by padding 0s at the end, but 0.1 on RHS is stored in double, hence the inequality. But if I go through this logic, the "if" in the above code should have given false, but istead it is true. Why?

like image 892
Avijeet Ghosh Avatar asked Jan 20 '26 15:01

Avijeet Ghosh


1 Answers

(Restricting the answer to IEEE754 although all floating point schemes supported by C mandate that the double set is a superset of the float set.)

0.1 is 0.1000000000000000055511151231257827021181583404541015625

0.1f is 0.100000001490116119384765625.

0.100000001490116119384765625 is promoted to a double, but it's the same number as all floats can be represented as doubles exactly.

So (double)(0.1f) is bigger than 0.1, accounting for the result.

like image 106
Bathsheba Avatar answered Jan 22 '26 19:01

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!