Python math is off by .000000000000045

Grant Edwards invalid at invalid.invalid
Wed Feb 22 15:48:34 EST 2012


On 2012-02-22, Alec Taylor <alec.taylor6 at gmail.com> wrote:

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

Oh good.  We haven't have this thread for several days.

> 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?

http://docs.python.org/tutorial/floatingpoint.html

Python uses binary floating point with a fixed size (64 bit IEEE-754
on all the platforms I've ever run across).  Floating point numbers
are only approximations of real numbers.  For every floating point
number there is a corresponding real number, but 0% of real numbers
can be represented exactly by floating point numbers.

> - Or is this a bug?

No, it's how floating point works.

If you want something else, then perhaps you should use rationals or
decimals:

http://docs.python.org/library/fractions.html
http://docs.python.org/library/decimal.html

-- 
Grant Edwards               grant.b.edwards        Yow! What I want to find
                                  at               out is -- do parrots know
                              gmail.com            much about Astro-Turf?



More information about the Python-list mailing list