[Pythonmac-SIG] Numeric issue (not Mac specififc?)
John W Baxter
jwblist@olympus.net
Mon, 9 Apr 2001 23:32:33 -0700
At 7:03 +0200 4/10/01, Stefan Witzgall wrote:
>Playing around I found the following:
>
>>>> 6666666666666.2+9
>6666666666675.2002
>>>> 66.2+9
>75.200000000000003
>>>> 66.2+9.0
>75.200000000000003
>>>> 0.2+9.0
>9.1999999999999993
>>>>
>
>Is this lack of accuracy documented, perhaps in the description of the
>types Python use? Is there a possibility to get a predictable accuracy or
>behavior, or is there a module out anywhere to do mathematical operations
>in a "better" way?
This is just the way binary floating point works. Numbers which we
decimillians "know" are exact generally aren't. [Eduroa doesn't like the
spelling of decimillians...I wonder why. ;-)]
Seriously, 75.2 is "obviously" exact...it can't be represented exactly in
binary floating point.
And you are correct: one should not compare computed binary floating point
numbers to zero, or to other constants, or to each other...one should
instead determine whether one number is close enough to another number.
"Comparing" includes the exit test of loops.
This only became "obvious" with recent Python versions which don't hide it
from us (by not rounding off). Before, one had little surprises like:
>>> (0.1 + 0.1 + 0.1) == 0.3
0
without the hints one gets now that something "strange" is going on.
To get more "reasonable" results, use print or other tools...try
print 6666666666666.2+9
--John
--
John Baxter jwblist@olympus.net Port Ludlow, WA, USA