Ask Your Question

Possible bug of sum function

asked 2016-04-11 12:15:50 -0500

jllb gravatar image

Consider the following code:

def s(n):
    return sum(k/n for k in range(n + 1))

L0 = s(2)

for n in range(2, 3):
    L1 = s(n)

The answers are (using sage 7.1):

print L0, L1
(3/2, 1)

In the second case sage is using the usual integer division of python 2.x while in the first one it is using the exact representation of rationals. Is this a known bug?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-04-11 13:32:15 -0500

tmonteil gravatar image

updated 2016-04-11 13:33:32 -0500

It is not a bug. When you write s(2), Sage preparse the 2 so that it is the Sage Integer 2, not the Python int 2. With such Sage integers, the division leads to a Sage Rational. Now, when you use the range function, it produces Python ints, which explains your problem. If you want to generate a list of Sage Integers, you should use the srange function instead of range.

edit flag offensive delete link more


Thank you, however I find this behavior at least strange. If n is a Sage Integer, I understand range(n) produces a list of Python integers. So in both cases the sum runs over a list of Python integers. However, in one case they are converted into Sage integers and in the other case they aren't. I don't understand why.

jllb gravatar imagejllb ( 2016-04-11 15:28:21 -0500 )edit

In your call L0=s(2), s gets called with a Sage integer, and dividing a sage integer by a python integer is defined by converting the python integer to a sage integer and then doing the division

In your second example, n in range(2,3), we have that n is a python integer, so when s executed, two python integers are divided. We never get a chance to adjust the result. It's indeed strange and confusing, but we can't do anything about it unless we heavily patch python. If we ever change to Python3, it will be slightly better (you'll get a float rather than a python integer back)

nbruin gravatar imagenbruin ( 2016-04-11 16:08:04 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2016-04-11 12:15:50 -0500

Seen: 51 times

Last updated: Apr 11 '16