'Python Error: RuntimeWarning: overflow encountered in double_scalars

I am running into the error in the title with the code below:

from scipy import special as sp
def func(x, n):
    coefs = [[0] * (n+1) for _ in range(n+1)]
    for i in range(n+1):
            for j in range(i+1):
                    if j <=x:
                            coefs[i][j] = sp.binom(i, j)
                    else:
                            sumation = 0
                            for k in range(x+1):
                                    sumation = sumation + coefs[i - k - 1][j - k]
                            coefs[i][j] = sumation

Running this with

print(func(10, 1500))

returns the error:

RuntimeWarning: overflow encountered in double_scalars
sum = sum + list[i - k - 1][j - k]

It works up until just past n = 1000

I am using python 3.6. I thought that numbers could be any size in this version of python, but I am new to it so I might just be missing something.

Any help with overcoming this would be appreciated.

Thank you



Solution 1:[1]

Some observations: first, it runs on my machine without error; second, the print(func(10, 1500)) call always prints None since func() doesn't return anything; third, it creates an 1501 by 1501 matrix-like structure but only operates on the first 11 elements of each row, leaving the last 1490 elements of each row set to 0 which seem odd, as if the index ranges aren't correct.

Fourth, you've redefined Python built-in function names as variables which isn't a good idea as you can't use them for their original purpose in the scope of your function:

>>> list
<class 'list'>
>>> sum
<built-in function sum>
>>> 

Fifth, are you aware that one of these indexes:

sum = sum + list[i - k - 1][j - k]

is going negative at times:

sum = sum + list[10][-5]

so you're accessing this row from the left end (where all the zeros are.)

Sixth, now that you added a call to sp.binom(i, j), it fails for me when I run it with the error in question. Are you aware that sp.binom() returns a numpy.float64 which can't size up like a Python integer.

I'm running Python 3.6.0 -- perhaps you could provide more information about your environment.

I thought that numbers could be any size in this version of python

The last row of list is:

[1, 746, 185755, 23157624, 1736848299, 87162383901, 3138960008701, 85259372826713, 1813040043422321, 31075927633744029, 439493479567385970, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

So number size doesn't appear to be an issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1