Python RuntimeWarning:在长标量中遇到溢出 [英] Python RuntimeWarning: overflow encountered in long scalars

查看:347
本文介绍了Python RuntimeWarning:在长标量中遇到溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手.在我最新的Python 2.7项目中,我遇到了以下问题:

I am new to programming. In my latest Python 2.7 project I encountered the following:

RuntimeWarning:long_scalars中遇到溢出

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

收益

RuntimeWarning: overflow encountered in long_scalars

在上面的示例中,发生这种情况是因为a是dtype int32,并且int32中可存储的最大值是2 ** 31-1.从10**10 > 2**32-1开始,求幂的数字大于int32中可以存储的数字.

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.

请注意,您不能依靠np.seterr(all='warn')来捕获所有溢出 numpy中的错误.例如,在32位NumPy上

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

在64位NumPy上:

while on 64-bit NumPy:

>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848

两者都失败,没有任何警告,尽管这也是由于溢出错误引起的.正确的答案是21!等于

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

据Numpy开发人员Robert Kern

与真正的浮点错误不同(硬件FPU设置了一个 旗帜 每当它执行溢出的原子操作时),我们需要 自己实现整数溢出检测.我们做 这 标量,而不是数组,因为实现起来太慢 为了 数组上的每个原子操作.

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.

因此,选择合适的dtypes负担很大,这样就不会发生任何操作溢出.

So the burden is on you to choose appropriate dtypes so that no operation overflows.

这篇关于Python RuntimeWarning:在长标量中遇到溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆