0

I don't understand how python2.7 checks for the 'less than' comparison operator.

For example if I run the following function

def f():
    P = 0.6
    while P <= 4.0:
           if P < 2.0:
                print(P)
                P += 0.2
                print(P)
                print("-")
            elif P < 10.0:
                P += 2.0

produces the following output:

  0.6
  0.8
  -
  0.8
  1.0 
  -
  1.0
  1.2
  -
  1.2
  1.4
  -
  1.4
  1.6
  -
  1.6
  1.8
  -
  1.8
  2.0
  -
  2.0
  2.2
  -

According to what I understand, I should never see the value of 2.2, but go directly to 4.0 after the value of 2.0. What am I missing? I am using Python 2.7.3 on a linux machine.

Thanks for the help.

Jelle V
  • 21
  • 3
  • It’s this kind of idea: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Ry- Apr 27 '18 at 17:32
  • Note that `2.2` and `2.1999999999999997` are not equal, please read the above links on floating point representation. In your case I would recommend comparing against `round(P, 2)` instead of just `P` – Cory Kramer Apr 27 '18 at 17:33
  • Specifically, `0.6 + 0.2 + 0.2 + 0.2 + 0.2 + 0.2 + 0.2 + 0.2 == 1.9999999999999998`, which is `< 2.0`, but `str(1.9999999999999998)` is `"2.0"` in Python 2. – Ry- Apr 27 '18 at 17:34
  • so then, why you need elif? – Ashlou Apr 27 '18 at 17:37

0 Answers0