Math irregularity ... is this normal?

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jul 4 20:50:06 EDT 2002


Some One Else <nospam at any.time> wrote:

: Hello!

: I just compiled and installed Python 2.2.1 on Linux-Mandrake 8.0.  When I 
: do the following:

:>>> 2/5.0
: 0.40000000000000002

: In  'Learning Python', a similar example says I should get the more logical 
: answer of 0.4.  Did I install something wrong? I can see where this could 
: result in creeping math errors.

Hello!

The behavior of displaying floating point numbers changed slightly
between Python 1.52 and Python 2.0 to reflect more of the nature of
floating point: almost all floating point numbers can't be represented
precisely on computers.  The Python tutorial has a good section that
taks more about floating point issues:

    http://www.python.org/doc/tut/node14.html


To make this inprecision more visible to programmers, the implementers
of Python 2.0 made a small change in Python's repr() string
representation function:

    http://www.amk.ca/python/2.0/

Look around Section 10, and you should see something about this.



By the way, if you call the 'str()' function on your number, Python
will display the number in a way that you'd expect:

###
>>> 2/5.0
0.40000000000000002
>>> str(2/5.0)
'0.4'
>>> print 2/5.0
0.4
###

and when you encounter the 'print' statement later on in Learning
Python, you'll find that it does an implicit str() of anything you
give it.



Hope this helps!





More information about the Python-list mailing list