1

When i run my code, the number turns into 42.0 (what it's supposed to do) but does not stop when it turns into 42.0 (though the if statement or while loop) how would i get my code to stop?

import time
def life(inp):
    inp = float(inp)
    while float(inp) != float(42):
        inp = inp*12/4/4+4+6.5
        if float(inp) == float(42) or inp == 42:
            print inp
            break
        print inp
        time.sleep(0.1)


life(6)
Infinidoge
  • 56
  • 7
  • 4
    comparing floating point numbers for strict equality is rarely a good idea - floating point inaccuracies make that highly problematic – UnholySheep Mar 21 '17 at 21:06
  • Because life has no sense. – B. M. Mar 21 '17 at 21:09
  • Possible duplicate of [How should I do floating point comparison?](http://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison) – Schorsch Mar 21 '17 at 21:51

1 Answers1

13

Because it isn't 42.0, which you can see by doing print '%.60f' % inp instead. Then you'll see that you're actually stuck at 41.999999999999985789145284797996282577514648437500000000000000.

Or with print repr(inp), which shows 41.999999999999986 (not the exact stored value, but it shows that it's not 42.0).

If you just do print inp or print str(inp) then Python shows a "nice version" of the number, which doesn't necessarily actually represent the number.

You might want to go for "close enough" instead, for example like this:

while abs(float(inp) - float(42)) > 1e-9:

Or check out this answer.

Community
  • 1
  • 1
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107