为什么在大于9的幂次中提升numpy数组会返回错误的结果?

为什么在大于9的幂次中提升numpy数组会返回错误的结果?,numpy,Numpy,我不明白为什么提高超过9的力量对我来说不起作用。看起来很简单:例如,我只是想用10的力量来提高10,但不管是什么原因,numpy都失败了。有什么问题吗 import numpy as np number = 10 arr = [number] print(np.power(np.array(arr),number)) # [1410065408] print([n**number for n in arr]) # [10000000000] 为什么在大于9的幂中提升numpy数组会返回错误的

我不明白为什么提高超过9的力量对我来说不起作用。看起来很简单:例如,我只是想用10的力量来提高10,但不管是什么原因,numpy都失败了。有什么问题吗

import numpy as np
number = 10
arr = [number]

print(np.power(np.array(arr),number)) # [1410065408]
print([n**number for n in arr]) # [10000000000]
为什么在大于9的幂中提升
numpy
数组会返回错误的结果

由于在
np.array
实例化时使用的隐式(从类型推断中假定)
dtype
,以及溢出副作用:

>>> np.power( np.array( arr, dtype = np.int64 ), 10 )
array([10000000000], dtype=int64)

>>> np.power( np.array( arr, dtype = np.int32 ), 10 )
array([-2147483648])

>>> np.power( np.array( arr, dtype = np.int   ), 10 )
array([-2147483648])

>>> np.power( np.array( arr                   ), 10 )
array([-2147483648])

>>> pass;     np.array( arr ).dtype
dtype('int32')

那么这个问题的解决方案是什么呢?显然,一个正确的、类型安全的
numpy.array
实例化,如上所述——使用
np.array(arr,dtype=np.int64)
和int64(在我的系统中,它是默认的)一起溢出,即使字体很长,它也会在19次方和20次方溢出。不要惊讶,这些都是基本事实。如果您寻求任意精度的数字表示,则可以使用
np.array(…,dtype=…)
来存储值。然而,这还不足以完成所有任意精度的数学运算,因为还需要使用适当的工具来表示这些数字(这远远超出了本文的范围)。你可能会在这里、StackOveflow或其他地方找到关于任意精度操作的更详细的帖子,如果有兴趣,还可以找到超过1E+4小数位的例子。