Comparing Same Float Values In C
strange output in comparison of float with float literal
Float addition promoted to double?
I read the above l
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.
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.
The first if
statement evaluates to true
, so IF
is printed. The other expressions aren't even checked.