Python math is off by .000000000000045

John Ladasky ladasky at
Sun Feb 26 19:24:14 EST 2012

Curiosity prompts me to ask...

Those of you who program in other languages regularly: if you visit, for example, do people ask this question about
floating-point arithmetic in that forum?  Or in comp.lang.perl?

Is there something about Python that exposes the uncomfortable truth
about practical computer arithmetic that these other languages
obscure?  For of course, arithmetic is surely no less accurate in
Python than in any other computing language.

I always found it helpful to ask someone who is confused by this issue
to imagine what the binary representation of the number 1/3 would be.

0.011 to three binary digits of precision:
0.0101 to four:
0.01011 to five:
0.010101 to six:
0.0101011 to seven:
0.01010101 to eight:

And so on, forever.  So, what if you want to do some calculator-style
math with the number 1/3, that will not require an INFINITE amount of
time?  You have to round.  Rounding introduces errors.  The more
binary digits you use for your numbers, the smaller those errors will
be.  But those errors can NEVER reach zero in finite computational

If ALL the numbers you are using in your computations are rational
numbers, you can use Python's rational and/or decimal modules to get
error-free results.  Learning to use them is a bit of a specialty.

But for those of us who end up with numbers like e, pi, or the square
root of 2 in our calculations, the compromise of rounding must be

More information about the Python-list mailing list