Python 3: RuntimeWarning with numpy.power

940 views Asked by At

When using numpy.power(2,N), where N is an integer, I encounter the following issue:

In[1] np.power(2,63)
Out[1] -9223372036854775808
RuntimeWarning: invalid value encountered in power

and even more strangely,

In[2] np.power(2,63)*2
Out[2] 0

This happens for all exponents greater than or equal to 63. I thought that large integer are not an issue in Python - what's wrong here, then?

1

There are 1 answers

0
MSeifert On BEST ANSWER

Large integers are not a problem with Python because Python only has one integer type and that is of arbitrary precision. But NumPy uses normal "C" data types and these have limited precision:

>>> 2 ** 63              # Python
9223372036854775808

>>> np.int64(2) ** 63    # NumPy
-9223372036854775808

On most systems 64bit is the highest precision integer type available with plain NumPy. So if you're dealing with larger numbers you could use float dtypes or simply use Python integers with normal lists or NumPy object arrays (not really recommended).