Python numpy数组中的整数溢出

Python numpy数组中的整数溢出,python,numpy,Python,Numpy,用这个代码我得到了这个答案。为什么我会得到负值 import numpy as np a = np.arange(1000000).reshape(1000,1000) print(a**2) 在您的平台上,np.arange返回一个数据类型为“int32”的数组: [[ 0 1 4 ..., 994009 996004 998001] [ 1000000 1002001 1004004 ...,

用这个代码我得到了这个答案。为什么我会得到负值

import numpy as np
a = np.arange(1000000).reshape(1000,1000)
print(a**2)

在您的平台上,np.arange返回一个数据类型为“int32”的数组:

[[         0          1          4 ...,     994009     996004     998001]
 [   1000000    1002001    1004004 ...,    3988009    3992004    3996001]
 [   4000000    4004001    4008004 ...,    8982009    8988004    8994001]
 ..., 
 [1871554624 1873548625 1875542628 ..., -434400663 -432404668 -430408671]
 [-428412672 -426416671 -424420668 ..., 1562593337 1564591332 1566589329]
 [1568587328 1570585329 1572583332 ..., -733379959 -731379964 -729379967]]
数组的每个元素都是32位整数。平方运算会导致不适合32位的结果。结果被裁剪为32位,但仍然被解释为32位整数,这就是为什么会看到负数

编辑:在这种情况下,可以通过在平方前构造一个数据类型为“int64”的数组来避免整数溢出:

In [1]: np.arange(1000000).dtype
Out[1]: dtype('int32')
请注意,在使用numpy时,您发现的问题是一个固有的危险。您必须小心选择数据类型,并且事先知道代码不会导致算术溢出。为了提高速度,numpy不能也不会在发生这种情况时警告您


有关此问题的讨论,请参阅numpy邮件列表。

numpy整数类型是固定宽度的,您可以看到整数溢出的结果。

python整数没有此问题,因为它们在溢出时会自动升级为python长整数

因此,如果您确实设法使int64溢出,一种解决方案是在numpy数组中使用python int:

导入numpy
a=numpy.arange(1000,dtype=object)
a**20

此问题的解决方案如下(摘自):

…类StringConverter.\u映射器(numpy/lib/\u iotools.py)的更改来自:

这解决了我在
numpy.genfromtxt
中遇到的类似问题

请注意,作者将此描述为“临时”和“非最佳”解决方案。然而,我使用v2.7没有副作用(还没有?!)

a=np.arange(1000000,dtype='int64').reshape(1000,1000)
import numpy
a=numpy.arange(1000,dtype=object)
a**20
{{{
 _mapper = [(nx.bool_, str2bool, False),
            (nx.integer, int, -1),
            (nx.floating, float, nx.nan),
            (complex, _bytes_to_complex, nx.nan + 0j),
            (nx.string_, bytes, asbytes('???'))]
}}}
{{{
 _mapper = [(nx.bool_, str2bool, False),
            (nx.int64, int, -1),
            (nx.floating, float, nx.nan),
            (complex, _bytes_to_complex, nx.nan + 0j),
            (nx.string_, bytes, asbytes('???'))]
 }}}