Strange output when comparing same float values?

2020-02-11 13:34发布

问题:

Comparing Same Float Values In C

strange output in comparison of float with float literal

Float addition promoted to double?


I read the above links on floating points, but even getting strange output.

#include<stdio.h>
int main()
{
    float x = 0.5;

    if (x == 0.5)
        printf("IF");

    else if (x == 0.5f)
        printf("ELSE IF");

    else
        printf("ELSE");
}

Now, according to the promotion rules, Shouldn't "ELSE IF" must be printed ?

But, here it is printing "IF"


EDIT : Is it because 0.5 = 0.1 in binary and everything is 0 after that and loss of precision hence no effects, so comparison IF returns true.

Had it been 0.1, 0.2, 0.3, 0.4, 0.6, 0.7.... , then Else If block returns true.


Pardon me asking same question, because I have read from the above links that floats comparison must never be done.

But, What is the reason of this unexpected behaviour ?

回答1:

Floating point numbers are never accurate.

This statement is wrong. Some floating point numbers are accurate, such as 1.0, 12345.0, 12345.5, -2.25. All these numbers can be represented as integers didived by a power of 2. All numbers that cannot also are not accurate.

In your specific case, float x = 0.5 results in x having the value 1.00000000 * 2^-1. When you compare this against double 0.5, both operands are converted to double, so the comparison becomes 1.000000000000000 * 2^-1 == 1.000000000000000 * 2^-1, which succeeds.

For float x = 0.1, it looks different. The value is stored as 1.01010101 * 2^-3 (or similar). Note that this is already not precise. When you compare this against double 0.1, the float is extended with zeros at the end, the comparison becomes 1.010101010000000 * 2^-3 == 1.010101010101010 * 2^-3, which fails.



回答2:

As you have read the links regarding problems with floating point types and comparisons, you are probably expecting that 0.5 is rounded during conversion and hence the comparison should fail. But 0.5 is a power of 2 and can be represented perfectly without any rounding in a float or double type variable. Therefore the comparison results in TRUE.

After your edited your question: Yes, if you took 0.1 or one of the other values you mention, you should run into the else part.



回答3:

The first if statement evaluates to true, so IF is printed. The other expressions aren't even checked.