simple math don't work like I expected

Andrew Dalke adalke at mindspring.com
Wed Jan 29 10:51:27 EST 2003


Elvis Zaichenok wrote:
> Please, could somebody explain why things work like this? Why 1.0<1?

> ....     if (a-1)<1:
> ....         print(str(a-1)+'<1')
> ....     a=a+0.005
> ....
> 0.99<1
> 0.995<1
> 1.0<1

Because str lies to you, to make the numbers look nice.

See

http://www.python.org/doc/current/tut/node14.html
http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp

The 'repr' function shows you the base 10 value closest
to the base 2 value used by the computer.

 >>> a = 1.99
 >>> while a < 2.01:
...     if (a-1) < 1:
...             print repr(a-1), '< 1'
...     a = a + 0.005
...
0.98999999999999999 < 1
0.99499999999999988 < 1
0.99999999999999978 < 1
 >>>

and you can see that "1.99" is not precisely representable
using your computer's floating point values.

					Andrew
					dalke at dalkescientific.com





More information about the Python-list mailing list