# range and division : unexpected behavior

Consider the following snippet :

N=5

# code 1
for n in range(N,N+1):
for k in range(0,n):
print k/n

print '-'*10

# code 2
n=N
for k in range(0,n):
print k/n


I was expecting code 1 and code 2 to print the same output. This is not the case :

0
0
0
0
0
----------
0
1/5
2/5
3/5
4/5


In the first case, k/n is Python-evaluated as an integer division, in the second case, k/n is Sage-evaluated as a fraction. Can someone elaborate please ?

I only notice that substituting srange(N,N+1) to range(N,N+1) fixes the problem.

edit retag close merge delete

Sort by » oldest newest most voted There is a difference between Sage and Python (2.x) concerning the division operator / . In Python 2.x the operator / returns the floor of the result of division if the operands are integers (Python ints). In Sage the operator / returns the result as rational number (if so) if the operands are Sage integers. The Python function range returns a list of Python integers. In your nested for loops all operands are Python ints, so you get the floor of the division result. In your second code example N (and therefor n) is an Sage integer, so you get the rational numbers as result.

The Sage function srange returns a list of Sage integers. With srange(N,N+1) in your first code n becomes a Sage integer.

You can see the difference by placing some print type(k) and print type(n) commands inside the loops.

more

Thanks, now the benefits of using srange is more apparent.