0

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

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69

5 Answers5

5

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

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.

bash.d
  • 13,029
  • 3
  • 29
  • 42
2

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")
Lefteris E
  • 2,806
  • 1
  • 24
  • 23
0

the given answers are right... on Dr Dobb's Andrew Koenig is writing about order relationship with floats, have a view:

its-hard-to-compare-floating-point-numbers

comparing-an-integer-with-a-floating-point1

Exceptyon
  • 1,584
  • 16
  • 23
  • I don't see the answer to the question at hand in these two articles. The answer is that `a` is `0.8f` and that `0.8f` is different from the double-precision constant `0.8`. – Pascal Cuoq Mar 26 '13 at 17:12
0

Everything is stored eventually in bits.... So floating points get rounded off in case their binary equivalents are recurring...

Darshan Shah
  • 57
  • 1
  • 7