Python doesn't know how to do math?

David Bolen db3l at fitlinxx.com
Thu Apr 25 18:40:45 EDT 2002


Chris Spencer <clspence at one.net> writes:

> 	I tested this using the Python command interpreter on a Windows XP box
> running:
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>> float(5)/float(100)
> 0.050000000000000003
> >>> 5.0/100.0
> 0.050000000000000003
> 
> 	Okay, I might not be a math genius, but this is most definately WRONG.
> What gives?  Anyone have insight into this little "feature" of Python floating
> point operations?

See http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp

With Python 2.2, a new appendix (B) was added to the tutorial covering
floating point issues.  You can also get to it online at
http://www.python.org/doc/current/tut/node14.html

The results you are seeing aren't precisely "wrong" (certainly not in
terms of binary floating point precision), it's just more detail than
you probably expect by default.  If you thought that computers using
binary floating point (the most typical nowadays) in lieu of BCD or
other decimal based formats could precisely represent base 10 numbers
the same way you might with pencil and paper, that was an erroneous,
but forgiveable, assumption :-)

If you want Python to "fib" to you about the result (as earlier
versions did by default), you can do:

   >>> print float(5)/float(100)
   0.05

instead.  The default output at the interpreter is to use repr() to
print an object, which shows the highest precision possible to best
assure that its output could be used to re-create the object.  The
print statement will use str() which is designed for "prettier" output
and will do some rounding.

But don't fool yourself into thinking that regardless of what is being
printed, the computer is thinking of the precise value 0.05 - it
isn't.  That's the nature of floating point computations in general.
And if you're going to be writing code dependent on floating point
computations, it's important that you recognize these limitations,
since it can cause you problems (e.g., a classic example is testing
explicitly against 0.0 following a floating point computation).

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list