Ask Your Question
0

Different results with for loop and while loop

asked 2019-11-15 23:35:56 +0100

ShreevatsaR gravatar image

While writing a Sage script, I ran into a strange case where code worked correctly with specific constants, but when I looped over them in a for loop, it no longer worked. After trying this and that, I found that a while loop did not have this problem! As this felt very strange, recording the question here as a possible "gotcha".

Here's the code:

var('z')
from collections import defaultdict
p = defaultdict(dict)

N = 30
for h in range(N): p[0][h] = z**h

def fill(w):
    for h in range(N - w):
        p[w][h] = w/(w+h)*p[w-1][h+1] + h/(w+h)*(p[w][h-1] if h>=1 else 0)

## This doesn't work:
# for w in range(1, N): fill(w)
## Instead we need the below:
w = 1
while w < N:
    fill(w)
    w += 1

In short, the problem is that for w in range(1, N): ... results in all zero polynomials, while w = 1; while w < N: ... does not.

edit retag flag offensive close merge delete

Comments

ShreevatsaR gravatar imageShreevatsaR ( 2019-11-16 02:07:12 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2019-11-15 23:38:34 +0100

ShreevatsaR gravatar image

Figured out the the reason as well: with

for w in range(1, N):
    fill(w)

the type of w is int, and so is the type of h inside the inner loop in fill. So something like w/(w+h) uses integer division (on ints), giving 0.

On the other hand, with

w = 1
while w < N:
    fill(w)
    w += 1

the type of w is Integer, so w/(w+h) results in a proper fraction and not 0.

edit flag offensive delete link more

Comments

You can use srange to get a range of Integer type integers.

nbruin gravatar imagenbruin ( 2019-11-16 03:18:26 +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: 2019-11-15 23:35:56 +0100

Seen: 1,110 times

Last updated: Nov 15 '19