得到numpy警告整数溢出

Dan*_*Dan 10 python numpy integer-overflow

主要使用python,我已经被宠坏了,不必担心整数溢出.现在我正在使用numpy,我不得不再次担心它.我想在溢出的情况下numpy错误,但它似乎不适用于int64.

import numpy
numpy.seterr(all='raise')
print("{:,}".format(numpy.prod([10]*50)))
# -5,376,172,055,173,529,600
print("{:,}".format(numpy.int64(3200000000) * numpy.int64(3200000000)))
# -8,206,744,073,709,551,616
print("{:,}".format(numpy.int32(320000) * numpy.int32(320000)))
# FloatingPointError: overflow encountered in int_scalars -- Finally getting an error!
Run Code Online (Sandbox Code Playgroud)

我总是可以添加dtype=object修复这些问题,但我认为int64在大多数情况下都是足够好的,它可能会因为难以检测的方式而失败.

为什么seterr只适用于int32?我可以让它适用于int64吗?

我可以找到的numpy.seterr文档的唯一部分可能暗示为什么会出现这种情况的原因如下:

请注意,对整数标量类型(如int16)的操作将像浮点一样处理,并受这些设置的影响.

但是数据类型文档中没有任何内容表明int32和int64在某种程度上在概念上是不同的.不确定int64是否被视为"整数标量类型".

Ram*_*uet 2

事实上,该行为似乎取决于 int 类型的大小。这是一个列表,其中包含您的案例并添加了更多案例(已设置numpy.seterr(all='raise'))。

In [25]: numpy.int(3200000000) * numpy.int(3200000000)
Out[25]: 10240000000000000000

In [26]: numpy.int8(3200000000) * numpy.int8(3200000000)
Out[26]: 0

In [27]: numpy.int16(3200000000) * numpy.int16(3200000000)
---------------------------------------------------------------------------
FloatingPointError                        Traceback (most recent call last)
<ipython-input-27-a6185c9da0fd> in <module>()
----> 1 numpy.int16(3200000000) * numpy.int16(3200000000)

FloatingPointError: overflow encountered in short_scalars

In [28]: numpy.int32(3200000000) * numpy.int32(3200000000)
---------------------------------------------------------------------------
FloatingPointError                        Traceback (most recent call last)
<ipython-input-28-a3909399b44a> in <module>()
----> 1 numpy.int32(3200000000) * numpy.int32(3200000000)

FloatingPointError: overflow encountered in int_scalars

In [29]: numpy.int64(3200000000) * numpy.int64(3200000000)
Out[29]: -8206744073709551616
Run Code Online (Sandbox Code Playgroud)