[Pythonmac-SIG] possible bug with division operator and floating point numbers

Gordon Worley redbird@rbisland.cx
Wed, 17 Jan 2001 17:02:55 -0500


At 12:03 AM -0800 1/17/2001, Johann Hibschman wrote:
>On Tue, 16 Jan 2001, Richard Gordon wrote:
>>  > it basically worked out to 4.0/5.0 .
>>  >which came back with the answer, "0.80000000000000004." Now I have been
>>  >out of school for a bit, but Ilearned that should be 0.8.
>>
>>  Maybe this has been covered here & I missed it, but you are certainly
>>  correct and it's certainly strange.
>
>No, this is correct.  Python 2.0 has switched to using the exact printable
>representation of numbers in interactive mode.  It now prints out what repr
>printed before, the number to all decimal places.  I do suspect that a better
>algorithm exists for this, though.
>
>What you're seeing is the fact that floating-point numbers aren't exact.
>That's just the way that floats are, on any platform.  Before, the interpreter
>hid this from you.  Now, it displays it in all its glory.
>
>You should never count on a float to be exact, and never test a float for
>equality.  The last digit is effectively random.

Since the original poster mentioned being new to Python, a bit of 
slicing will take care of display problems, though won't fix the 
number as a float:

num = 4.0 / 5.0
`num`[:-1]

slices off that last 4, which is easy enough.  Something is the 
matter, though, because:

float(`num`[:-1])

yields

0.80000000000000004

and even just typing 0.8 in the interpreter returns the above number. 
There is bound to be a work around, but should be discussed 
elsewhere, since it isn't Mac specific.
-- 
Gordon Worley
http://www.rbisland.cx/
mailto:redbird@rbisland.cx
PGP:  C462 FA84 B811 3501 9010  20D2 6EF3 77F7 BBD3 B003