weird math errors in python 2.1.1

Jeff Shannon jeff at ccvcorp.com
Wed Aug 29 17:24:55 EDT 2001


andrew wrote:

> in interactive interpreter, i get these results:
>
> >>> 21.0 /5
> 4.2000000000000002
> [...snip...]
> anyone else seeing this?  is this a known bug?

It's not so much a bug, as it is a limitation of binary floating-point
arithmetic.  There are some decimal numbers that are not precisely
representable in binary floating point (just as there are some binary fp
numbers that aren't decimal-representable).  If you truly need precision in
your decimals, you should use fixed-point arithmetic (I believe there's a
FixedPoint.py available somewhere for this).  There are projects underway
to provide Python with a true Rational number type, but those are
incomplete as of yet.  And, really... for most uses of floating point, the
current system is good enough.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list