# Possible bug of sum function

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 close merge delete

Sort by » oldest newest most voted

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.

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.

1

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)