HELP: restore my faith in Python

William Park parkw at better.net
Fri Mar 3 14:37:55 EST 2000


On Fri, Mar 03, 2000 at 02:06:46PM -0500, Holton, Steven [NCRTP:6125:EXCH] wrote:
> I'm trying to learn Python, and wrote this script last night.  I was not 
> expecting to see this behavior, and my faith is severely shaken:
> 
> nose-46> python
> Python 1.5.2 (#1, Sep 17 1999, 20:15:36)  [GCC egcs-2.91.66
> 19990314/Linux (egcs- on linux-i386
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> limit = 5
> >>> for target in range(10):
> ...    n=((target/(limit+0.0))-(target/limit))*limit
> ...    print target, n, int(n)
> ... 
> 0 0.0 0
> 1 1.0 1
> 2 2.0 2
> 3 3.0 3
> 4 4.0 4
> 5 0.0 0
> 6 1.0 0     <=== huh?
> 7 2.0 1     <=== et tu Brutus?
> 8 3.0 3
> 9 4.0 4
> 
> Column 1 is the index, column 2 is 'n' as floating, and column 3 is
> 'n' as an integer.  Except that it ain't.
> 
> Can anyone explaing to me why index 6 and 7 aren't what I'm expecting 
> them to be?

The answer is round-off error.  Try 
    print "%d %.20g %d" % (target, n, int(n))

--William




More information about the Python-list mailing list