'RuntimeWarning: overflow encountered in scalar add': %timeit causing memory overflow

53 Views Asked by At

I was trying to calculate the cumulative sum of an array using the inbuilt np.cumsum() function vs a normal for loop and wanted to compare the results of %timeit. I'm encountering a weird result: before adding %timeit I get the right array and right sum, but adding %timeit is causing a scalar add overflow.

Here's the code:

cum_sum_arr = np.arange(1, 11)
def sum_f(arr):
    for i in np.arange(1, len(arr)):
        arr[i] += arr[i - 1]
    return arr
%timeit sum_f(cum_sum_arr)

This is the output without %timeit: array([ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55])

And with %timeit:

array([                   1,               811114,         328953366055,
          88939779487022460, -5773924544142308493,  -191197189035549726,
       -3390348287261219883, -1783318713650684592, -5145253417946954230,
       -6145597777128988204])

The error I received:

/var/folders/h4/jqqs40kd4pq3rbts__5zgkkr0000gn/T/ipykernel_24284/3552893438.py:3: RuntimeWarning: overflow encountered in scalar add
  arr[i] += arr[i - 1]

I am running this on Jupyter Notebook.

0

There are 0 best solutions below