Python RuntimeWarning:长标量中遇到溢出 [英] Python RuntimeWarning: overflow encountered in long scalars
问题描述
我是编程新手.在我最新的 Python 2.7 项目中,我遇到了以下问题:
<块引用>RuntimeWarning: long_scalars 中遇到溢出
有人可以详细说明这是什么意思以及我可以做些什么来解决这个问题吗?
代码通过了,但我不确定忽略警告是否是个好主意.
它发生在像这样的追加过程中:
SomeList.append(VeryLongFormula)
这是一个发出相同警告的示例:
将 numpy 导入为 npnp.seterr(all='warn')A = np.array([10])a=A[-1]一个**
收益
RuntimeWarning:long_scalars 中遇到溢出
在上面的例子中,发生这种情况是因为a
是dtype int32
,并且int32
中可存储的最大值是2**31-1.由于 10**10 >2**32-1
,取幂的结果是一个比int32
可以存储的数字更大的数字.
请注意,您不能依赖 np.seterr(all='warn')
来捕获所有溢出numpy 中的错误.例如,在 32 位 NumPy
在 64 位 NumPy 上:
<预><代码>>>>np.multiply.reduce(np.arange(21)+1)-4249290049419214848两者都在没有任何警告的情况下失败,尽管这也是由于溢出错误.正确答案是21!等于
在[47]中:导入数学在 [48]: math.factorial(21)出[50]:51090942171709440000L
据 numpy 开发人员 Robert Kern 称,><块引用>
不像真正的浮点错误(硬件 FPU 设置一个旗帜每当它执行溢出的原子操作时),我们需要自己实现整数溢出检测.我们这样做这标量,但不是数组,因为实现起来太慢为了数组上的每个原子操作.
因此,选择合适的dtypes
使操作不会溢出.
I am new to programming. In my latest Python 2.7 project I encountered the following:
RuntimeWarning: overflow encountered in long_scalars
Could someone please elaborate what this means and what I could do to fix that?
The code runs through, but I'm not sure if it is a good idea to just ignore the warning.
It happens during an append process like:
SomeList.append(VeryLongFormula)
Here's an example which issues the same warning:
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
yields
RuntimeWarning: overflow encountered in long_scalars
In the example above it happens because a
is of dtype int32
, and the maximim value storable in an int32
is 2**31-1. Since 10**10 > 2**32-1
, the exponentiation results in a number that is bigger than that which can be stored in an int32
.
Note that you can not rely on np.seterr(all='warn')
to catch all overflow
errors in numpy. For example, on 32-bit NumPy
>>> np.multiply.reduce(np.arange(21)+1)
-1195114496
while on 64-bit NumPy:
>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848
Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals
In [47]: import math
In [48]: math.factorial(21)
Out[50]: 51090942171709440000L
According to numpy developer, Robert Kern,
Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.
So the burden is on you to choose appropriate dtypes
so that no operation overflows.
这篇关于Python RuntimeWarning:长标量中遇到溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!