1

I've been learning programming in python for the last two weeks and it's going great so far. But now I'm stuck and can't seem to find an answer. I found a really weird behaviour of a while loop, I just can't wrap my head around.

x=0
step_size=0.2

while x<2:
    print x
    x+=step_size

This code prints:

0
0.2
0.4
...
1.8
2.0

2.0 should not be printed, right? When x becomes 2.0 the statement "x<2" is false, therefore the loop should exit and never print 2.0.

And now for the really weird part: it works with other numbers. Step_size=0.4 prints up to 1.6, step_size=0.1 up to 1.9. Using "x<1" as a statement and step_size=0.2 also works.

What am I missing?

Best regards, Leo

Edit: I'm using python 2.7.5 and the default Idle Editior v2.7.5

1 Answers1

3

It's floating point arythmetic. Output in console for python 3.6

0
0.2
0.4
0.6000000000000001
0.8
1.0
1.2
1.4
1.5999999999999999
1.7999999999999998
1.9999999999999998
Fildor
  • 14,510
  • 4
  • 35
  • 67
vencaslac
  • 2,727
  • 1
  • 18
  • 29