3

python code:

x=0.35
while (x<0.45):
    x=x+0.05
    print x,"<",0.45, x<0.45

below is the output:

0.4 < 0.45 True
0.45 < 0.45 True
0.5 < 0.45 False

Why 0.45<0.45 is true?

Paul
  • 26,170
  • 12
  • 85
  • 119
Tim
  • 355
  • 1
  • 8
  • 3
    http://docs.python.org/2/tutorial/floatingpoint.html – georg Oct 27 '13 at 16:50
  • Floating point problems, look them up. Floats are **not** exact representations. – Wrikken Oct 27 '13 at 16:51
  • this is a general computing problem and is found in other languages too, see: http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken – Paul Oct 27 '13 at 16:52

2 Answers2

7

Because you're actually comparing:

0.44999999999999996 < 0.45

Demo:

>>> x=0.35
>>> while (x<0.45):
        x = x+0.05
        print repr(x),"<",0.45, x<0.45
...     
0.39999999999999997 < 0.45 True
0.44999999999999996 < 0.45 True
0.49999999999999994 < 0.45 False

print calls str on floats, which prints a human friendly version:

>>> print 0.44999999999999996
0.45
>>> print str(0.44999999999999996)
0.45
>>> print repr(0.44999999999999996)
0.44999999999999996
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 5
    @user62367 It's not related to python, read: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Ashwini Chaudhary Oct 27 '13 at 16:51
1

This is called floating point error. It arises from the fact that you want to represent infinite amount of numbers with finite amount of bytes. So adding one floating point number with another will result in a floating point number that might be just close to the actual mathematical result. "Just close" might mean deviation of 0.0000001 or so to the expected result. You can read more about floating point errors here: http://support.microsoft.com/kb/42980

Lachezar
  • 6,523
  • 3
  • 33
  • 34