This is because 0.25 is a power of two (i.e. 2^-2), while 0.8 is not. Only exact sums of powers of two can be represented exactly; all other numbers, including 0.8, are represented as an approximation, which has a different precision between float
and double
. The 0.8
in a==0.8
is a double
, while a
is a float
. Their representations are different, and so are their values.
float value condition [duplicate]
-
29-03-2022 - |
Question
I worked out the following code and got a bizarre output. Can anyone explain how it works?
main()
{
float a=0.8;
float b=0.25;
if(a==0.8)
printf("HELLO")
if(b==0.25)
printf("WORLD")
}
And the output that I got is surprisingly
WORLD
thanks in advance
Solution
OTHER TIPS
You must never compare float
-values against absolute values as you did. There are usually slight rounding errors, as a float is represented according IEEE 754 and the machine is not capable of providing exact float-values.
Have a look here for your explanation and especially the rounding-rules.
you are comparing float against double. Try putting an f after the number
if(a==0.8f)
printf("HELLO")
if(b==0.25f)
printf("WORLD")
the given answers are right... on Dr Dobb's Andrew Koenig is writing about order relationship with floats, have a view:
Everything is stored eventually in bits.... So floating points get rounded off in case their binary equivalents are recurring...