Python 3: RuntimeWarning numpy.power

Python 3: RuntimeWarning with numpy.power

当使用 numpy.power(2,N) 时,其中 N 是一个整数,我遇到了以下问题:

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

更奇怪的是,

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

所有大于或等于 63 的指数都会发生这种情况。我认为大整数在 Python 中不是问题 - 那么这里有什么问题吗?

大整数对于 Python 不是问题,因为 Python 只有一种整数类型并且具有任意精度。但是 NumPy uses normal "C" data types 这些精度有限:

>>> 2 ** 63              # Python
9223372036854775808

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

在大多数系统上,64 位是普通 NumPy 可用的精度最高的整数类型。因此,如果你要处理更大的数字,你可以使用 float dtypes 或者简单地使用 Python 整数和普通列表或 NumPy 对象数组(不推荐)。