PDA

View Full Version : python : testing condition on numbers



wlourf
September 21st, 2010, 06:26 PM
Hello python's gurus !

With this simple code :

x=19.9
while x<20.1:
x+=0.01
print x, x==20,x==20.0
i except to have an output like this :

...
19.95 False False
19.96 False False
19.97 False False
19.98 False False
19.99 False False
20.0 True True
20.01 False False
20.02 False False
20.03 False False
...
but values are always set to False.

I know I miss something but don't know what ! I try to use float long bur without success.

NB : With str(x)=="20.0", that's ok but I'm looking for a more "clean" solution.

Thanks for any help !

Bachstelze
September 21st, 2010, 06:33 PM
Rounding errors. ;)


>>> x = 19.9
>>> while x < 20:
... x += 0.01
... print x, x == 20, x == 20.0
...
19.91 False False
19.92 False False
19.93 False False
19.94 False False
19.95 False False
19.96 False False
19.97 False False
19.98 False False
19.99 False False
20.0 False False
>>> x
20.000000000000014


Clean solution: work with integers.

wlourf
September 21st, 2010, 06:43 PM
arrrrh ok
on my computer, output is

20.10000000000003To work with integers, is this the correct way ?

x=1990
while x<2010:
x+=1
print x/100.0, x/100.0==20.0
what do you think ?

Bachstelze
September 21st, 2010, 06:48 PM
This is fine. 2000/100.0 does exactly equal 20. You don't really need to divide, though, just test for x == 20*100.

wlourf
September 21st, 2010, 06:55 PM
thanks ! et bonjour Bordeaux !

StephenF
September 21st, 2010, 11:19 PM
Comparing binary floating point numbers for equality based on presumptions derived from base 10 arithmetic is not a good idea. It's one of the traps new programmers fall into.

Fortunately Python has a module for floating point arithmetic in base 10 that will take those neat often rounded for human consumption numbers and play nice with them.
http://docs.python.org/library/decimal.html