Python math is off by .000000000000045
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
> 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:
Some languages hide the error by printing fewer decimals than they use
> -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
>>> from fractions import Fraction
>>> 1800 - 1041 - Fraction(55574, 100) + Fraction(53074, 100)
- Fraction(79495, 100)
>>> float(1800 - 1041 - Fraction(55574, 100) + Fraction(53074, 100)
- Fraction(79495, 100))
More information about the Python-list