3.2*2 is 9.6 ... or maybe it isn't?

Michael Torrie torriem at gmail.com
Thu Jun 25 14:41:13 EDT 2009

Bojan Sudarevic wrote:
> The first thing I typed into it was 3.2*3 (don't ask why I typed *that*, 
> I don*t know, I just did). And the answer wasn't 9.6.
> Here it is:
>>>> 3.2*3
> 9.6000000000000014

I'm surprised how often people encounter this and wonder about it.  As I
began programming back in the day using C, this is just something I grew
up with (grudging acceptance).

I guess PHP artificially rounds the results or something to make it seem
like it's doing accurate calculations, which is a bit surprising to me.
We all know that IEEE floating point is a horribly inaccurate
representation, but I guess I'd rather have my language not hide that
fact from me.  Maybe PHP is using BCD or something under the hood (slow
but accurate).

If you want accurate math, check out other types like what is in the
decimal module:

>>> import decimal
>>> a=decimal.Decimal('3.2')
>>> print a * 3

More information about the Python-list mailing list