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

Chris Barker cbarker@jps.net
Thu, 18 Jan 2001 11:06:28 -0800


Gordon Worley wrote:
>  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.

Yes, it should, but since we're here now:

Nothing is the matter. eight tenths can not be exactly represented as a
float in base two, even though it can be with only 2 digits in base ten.
See my previous post. This, by the way has nothing to do with Python,
and you will have the same effect in any language on all binary
arithmetic machines, which is most, unless the language has specific
support for base ten arithmetic (I have never heard of one that does,
but I wouldn't be surprised if it exists)

By the way, another solution to at least the interation problem is to
generate your list ahead of time with arrayrange (need Numeric, but I
really wish Python had a standard range that could deal with floats)

from Numeric import *

for x in arange(0,1.1,.1):
	print x


Note another interesting thing about how Python 2.0 prints:

>>> 0.1
0.10000000000000001
>>> x = 0.1
>>> print x
0.1
>>>                    

So, if you print a variable, rather than a direct computation, you get
it reaonably rounded. It's the difference between repr and str:

>>> print repr(0.1)
0.10000000000000001
>>> print str(0.1)
0.1
>>>            

Curious.

-Chris


-- 
Christopher Barker,
Ph.D.                                                           
cbarker@jps.net                      ---           ---           ---
http://www.jps.net/cbarker          -----@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Water Resources Engineering       ------   @    ------   @   ------   @
Coastal and Fluvial Hydrodynamics -------      ---------     --------    
------------------------------------------------------------------------
------------------------------------------------------------------------