This math scares me
Remco Gerlich
scarblac at pino.selwerd.nl
Mon Mar 12 17:56:47 EST 2001
costas at springmail.com <costas at springmail.com> wrote in comp.lang.python:
> Ok, I can see maybe division having problems. But why does addition of
> the two numbers below:
>
> 5.01+5.54
>
> give me this?
>
> 10.550000000000001
>
> I hope its some setting that can take care of this. I am using Python
> under Windows 98.
It's worse than that. Try:
>>> 5.01
5.0099999999999998
The number is stored in binary. It's not possible to represent everything in
a finite number of binary digits (just like you can't represent 1/3 in a
finite number of decimal digits - you don't protest either when you see
0.3333333333333333, do you? It's just as wrong).
This is not a Python problem, this is due to the way computers store
floating point numbers.
If you can avoid them, don't use floats. If you're working with money, count
cents instead (and use longs if you have numbers over a few hundred million
cents).
--
Remco Gerlich
More information about the Python-list
mailing list