Strange behavior of int()

Brian bkrisler at gmail.com
Thu Jan 26 21:42:34 EST 2006


Hello,

Can someone tell me what I am doing wrong in this code.

If I create a file change.py with the following contents:

def intTest(M, c):
        r = M
        for k in c:
                print 'int(r/k) = ', int(r/k), 'r =', r, 'k =', k, 'r/k
=', r/k
                r = r - (k*int(r/k))

intTest(2.30, [0.25, 0.10, 0.05, 0.01])

and execute it, I get the output:

int(r/k) =  9 r = 2.3 k = 0.25 r/k = 9.2
int(r/k) =  0 r = 0.05 k = 0.1 r/k = 0.5
int(r/k) =  0 r = 0.05 k = 0.05 r/k = 1.0
int(r/k) =  4 r = 0.05 k = 0.01 r/k = 5.0

Why is int(r/k), where r = 0.5 and k = 0.5 = 0?  Shouldn't it be 1?
And why is the last one = 4 and not 5?

If I execute a similar command from the command line, it works just
fine:
>>> int(0.05/0.05)
1

I have tested this on Linux, python 2.3.2 and 2.4.1 and Windows python
2.4.2
all with the same results.

I think I am doing something wrong in this line:
r = r - (k*int(r/k))

Thanks for any help.

Brian




More information about the Python-list mailing list