2010-05-04

Why don’t my floating-point numbers add up?

Recently happened upon this friendly site explaining the issues regarding floating-point math on binary computers and thought it useful.  As I'm sure you're aware it takes special talent to take a complicated subject and present it in an easy to understand fashion.

The article may be found below:
Since there is no page specifically for Python at the site, I thought I'd whip up this complement to the piece.  Below is an example for the language.  Note, that first half illustrates standard floating-point math and its associated issues.  The second half uses the decimal module to alleviate them. The drawback, as always a cost in performance.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Python 2.6.2 ...
>>>
>>> .1 + .2
0.30000000000000004
>>> .33*3
0.98999999999999999

>>> from decimal import Decimal
>>>
>>> Decimal('.1') + Decimal('.2')
Decimal('0.3')

Further Reading:

No comments:

Post a Comment