round(22.47,2) gives 22.469999999999999?

Helmut Jarausch jarausch at skynet.be
Thu Aug 7 03:42:11 EDT 2003


Eric van Riet Paap wrote:
> Hi,
> 
> On python2.1.3, python2.2.1 and python2.2.3 round(22.47,2) gives 
> 22.469999999999999 . Does anyone know if this is a bug or some weird, yet 
> unexpected, behaviour?

You're asking too much. There simply is no number 22.47 representable in
binary arithmetic with a finite number of bits. Remember most current
CPUs use binary and not decimal arithmetic.
So 22.469999999999999 is the best you can get and it doesn't make sense 
to print a rounded number with many more digits after the decimal point.

If you printed

print '%6.2f' % 22.47

you got '22.47'
so this limited precision (nearly 16 decimal digits)
doesn't hurt.
You still could write a fix-point class which internally
store the value multiplied by 10**d with a given 'd'.
You'd have to overload the standard math operators (and perhaps 
functions) and especially the '__str__' method.



-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany





More information about the Python-list mailing list