First time here? Check out the FAQ!

Ask Your Question
1

range and division : unexpected behavior

asked 8 years ago

candide gravatar image

updated 8 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
3

answered 8 years ago

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.

Preview: (hide)
link

Comments

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

candide gravatar imagecandide ( 8 years ago )

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: 8 years ago

Seen: 817 times

Last updated: Mar 27 '16