Python math is off by .000000000000045

Jussi Piitulainen jpiitula at ling.helsinki.fi
Wed Feb 22 13:44:52 EST 2012


Alec Taylor writes:

> Simple mathematical problem, + and - only:
> 
> >>> 1800.00-1041.00-555.74+530.74-794.95
> -60.950000000000045
> 
> That's wrong.

Not by much. I'm not an expert, but my guess is that the exact value
is not representable in binary floating point, which most programming
languages use for this. Ah, indeed:

>>> 0.95
0.94999999999999996

Some languages hide the error by printing fewer decimals than they use
internally.

> Proof
> http://www.wolframalpha.com/input/?i=1800.00-1041.00-555.74%2B530.74-794.95
> -60.95 aka (-(1219/20))
> 
> Is there a reason Python math is only approximated? - Or is this a bug?

There are practical reasons. Do learn about "floating point".

There is a price to pay, but you can have exact rational arithmetic in
Python when you need or want it - I folded the long lines by hand
afterwards:

>>> from fractions import Fraction
>>> 1800 - 1041 - Fraction(55574, 100) + Fraction(53074, 100)
         - Fraction(79495, 100)
Fraction(-1219, 20)
>>> -1219/20
-61
>>> -1219./20
-60.950000000000003
>>> float(1800 - 1041 - Fraction(55574, 100) + Fraction(53074, 100)
         - Fraction(79495, 100))
-60.950000000000003



More information about the Python-list mailing list