views:

144

answers:

4

Possible Duplicate:
How is floating point stored? When does it matter?

I was wondering what's the reason for the next behavior in Python:

>>> print(0.1 + 0.1 + 0.1 - 0.3)
5.55111512313e-17

To fix that one must use decimal instead:

>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
+2  A: 

The problem here is that decimal fractions cannot be represented exactly in binary floating point numbers.

The reason for this is the same as why fractions like one third cannot be represented exactly in the decimal number system (to finite precision at least.)

The decimal type usually represents a scaled integer, and is designed specifically for this type of problem. I'm guessing its something similar in Python.

Patrick McDonald
I have the same behavior in ruby with the code above, BUT puts 0.1 + 0.1 + 0.1 + 0.1 - 0.4 returns 0.0 as expected!
sled
@sled: Python also returns 0.0 for `0.1 + 0.1 + 0.1 + 0.1 - 0.4`.
badp
so why is it not working for 0.1 + 0.1 + 0.1 - 0.3 then?
sled
+4  A: 

This is because by default 0.1 is a float and decimal numbers cannot be exactly represented by floats.

Unlike float the Decimal type is not implemented using a C double and instead avoids hardware based binary floating point arithmetic in order to behave exactly as you would expect.

For a detailed discussion of this read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Dave Webb
A: 

Floating point rounding error. See this.

James