# Different results with for loop and while loop

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

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

Sort by ยป oldest newest most voted

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.

more

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

( 2019-11-16 03:18:26 +0100 )edit