I have the following code:
import numpy
def numpysum(n):
a = numpy.arange(n) ** 2
b = numpy.arange(n) ** 3
c = a + b
return c
size = 3000
c = numpysum(size)
When running, I get the error:
D:\Work\programming\python\test_1\src\test1_numpy.py:6: RuntimeWarning: invalid value encountered in power
b = numpy.arange(n) ** 3
Note that the following numpyless function works fine:
def pythonsum(n):
a = list(range(n))
b = list(range(n))
c = []
for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])
return c
I guess it happens because I try to raise a large number to power three. What can I do, beside working with floating point numbers?
I am working with Python 3.2.
numpy is actually looking out for you on this one. Unlke in standard Python, its integer operations don’t work on arbitrary-precision objects. I’d guess you were running a 32-bit python, because the same operations don’t overflow for me:
but they will eventually. Even easier to see if you control the size of the type manually:
where things improve as the number of bits increases. If you really want numpy array operations on Python arbitrary-size integers, you can set dtype to object: