[Edu-sig] Math weirdness?

Christopher A. Craig com-nospam@ccraig.org
03 Oct 2001 14:58:51 -0400


Robert Rickenbrode II <rkr_ii@yahoo.com> writes:

> Hey folks, can someone explain these to me:
> 
>  >>> import math
>  >>> math.pi
> 3.1415926535897931
>  >>> round (math.pi, 3)
> 3.1419999999999999
>  >>>
> 
> 
> and this:
> 
>  >>> 10./3
> 3.3333333333333335

These are floating point numbers.  They do not (and cannot) map to
decimal numbers with 100% precision.  Please see the FAQ at
http://www.python.org/doc/FAQ.html#4.98

There are BCD modules available if you really need your numbers to be
decimal, but you pay a price in performance.  I haven't ever needed
this, so I can't point you to one.

If you really need rationals you can use a rational number module of
which there are several good ones available.  I wrote a module which
is currently in testing called crat
(http://prdownloads.sourceforge.net/pythonic/crat-0.4.tar.gz).  The
mxNumber (http://www.lemburg.com/files/python/mxNumber.html) module
contains a rational type based on the GNU Multiprecision Library
(gmp).  There are also modules available called surd and yarn, but I
haven't seen them since the ftp.python.org re-org.  For these you will
pay an even bigger performance price.

I can't help you with irrational numbers like pi.  They by definition
can't be represented with 100% precision.  (Except, of course, by
saying "pi")

-- 
Christopher A. Craig <com-nospam@ccraig.org>
"The shortest distance between two points is usually torn up." Frank Walsh