simple math don't work like I expected

Peter Hansen peter at engcorp.com
Wed Jan 29 16:51:48 CET 2003


Elvis Zaichenok wrote:
> 
> Please, could somebody explain why things work like this? Why 1.0<1?
> 
> Python 2.2 (#1, Apr 12 2002, 15:29:57)
> [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> a=1.99
> >>> while a<2.01:
> ...     if (a-1)<1:
> ...         print(str(a-1)+'<1')
> ...     a=a+0.005
> ...
> 0.99<1
> 0.995<1
> 1.0<1

Try this instead, then read the FAQ entry at 
http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp

> >>> 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

The call to str() is converting the floating point value, which is not
quite 1.0, into a "nice" format for presentation to the user.  repr()
doesn't try to do this, so you will see the "true" values (but see the
FAQ to understand why "true" is a lie too.)

-Peter




More information about the Python-list mailing list