Ask Your Question
1

range and division : unexpected behavior

asked 2016-03-27 11:28:01 +0100

candide gravatar image

updated 2016-03-29 09:05:54 +0100

slelievre gravatar image

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

1 Answer

Sort by ยป oldest newest most voted
3

answered 2016-03-27 12:33:33 +0100

ndomes gravatar image

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.

edit flag offensive delete link more

Comments

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

candide gravatar imagecandide ( 2016-03-27 12:57:40 +0100 )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

1 follower

Stats

Asked: 2016-03-27 11:28:01 +0100

Seen: 786 times

Last updated: Mar 27 '16