Reputation: 33
I try to implement a visual illustration of Pascal's triangle with Python Mode for Processing for MAC OS X. One of the necessary steps is, of course, the calculation of the binomial coefficients in each row of the triangle. I chose to do it in a recursive way instead of calculating factorials. My code works well in Jupyter, but produces different outcomes in Processing. Does anybody know why and how I can fix the problem?
rows = 301
pascal=[[1], [1,1]]
for i in range (rows):
last_row = pascal[len(pascal)-1]
next_row = [1] +[last_row[i]+last_row[i+1] for i in range(len(last_row)) if i < len(last_row)-1] +[1]
pascal.append(next_row)
print (pascal[35][16])
The code produces the correct results when executed in Jupyter, but has different results in Processing. The problems begin in row 35 of the triangle (countig starts from 0). The 16th element in this row should be 4059928950 but Processing calculates -235038346. And from then on, the calculations in Processing seem to be often wrong.
Upvotes: 3
Views: 234
Reputation: 52008
The most principled approach would be to find a big integer library that you can call from Jython, but since all you need is addition, it is easy to write your own function which will take two base 10 string representations of positive integers and return the string representation of their sum:
rows = 301
def add_nums(s1,s2):
#reverse strings and 0-pad to be of the same length
s1 = s1[::-1]
s2 = s2[::-1]
s1 += '0'*(max(len(s1),len(s2)) - len(s1))
s2 += '0'*(max(len(s1),len(s2)) - len(s2))
dsum = []
c = 0 #carry
for d1,d2 in zip(s1,s2):
a,b = int(d1), int(d2)
c,r = divmod(a+b+c,10)
dsum.append(str(r))
if c > 0: dsum.append('1')
return ''.join(reversed(dsum))
pascal=[['1'], ['1','1']]
for i in range (rows):
last_row = pascal[len(pascal)-1]
next_row = ['1'] +[add_nums(last_row[i],last_row[i+1]) for i in range(len(last_row)) if i < len(last_row)-1] +['1']
pascal.append(next_row)
print (pascal[35][16]) #prints 4059928950
Upvotes: 1