gpt4 book ai didi

Python 运行时警告 : overflow encountered in long scalars

转载 作者:IT老高 更新时间:2023-10-28 20:38:15 29 4
gpt4 key购买 nike

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

RuntimeWarning: overflow encountered in long_scalars

谁能详细说明这意味着什么以及我可以做些什么来解决这个问题?

代码运行通过,但我不确定忽略警告是否是个好主意。

它发生在 append 过程中,例如:

SomeList.append(VeryLongFormula)

最佳答案

这是一个发出相同警告的示例:

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 中可以存储的数字。

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

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

在 64 位 NumPy 上:

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

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

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.

所以你有责任选择合适的dtypes,以免操作溢出。

关于Python 运行时警告 : overflow encountered in long scalars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7559595/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com