python - 如何检查数字溢出而不在 Python 中收到警告?

标签 python numpy overflow

我有一个表达式,它会因某些参数值而溢出。在这种情况下,我已经使用笔和纸得出了渐近结果应该是什么,当我遇到这种情况时,我只是用我的解析表达式替换。

目前我的代码是这样的:

values = ExpressionThatOverFlows()
# Check the ones that overflow
indOverFlow = isnan(values)
# Set them to the values I derived by pen and paper
values[indOverFlow] = derivedValues

我的问题是 I/O 因“警告”而爆炸。我知道它警告我是件好事,但我已经明确地处理了它,所以我想让他们闭嘴。请注意,我不想让所有类型的“溢出”警告静音,只让此处的警告静音。我认为这样的事情会奏效,但事实并非如此:

try:
   values = ExpressionThatOverFlows()
except Warning:
   pass
# and the rest of the code as it is

我已经检查过了,但我似乎只是找到了如何在整个 session 期间或永远消除这些警告的方法,但正如我指出的那样,这不是我想要的。

感谢您的帮助,非常感谢。

编辑:这是一个更小的代码,它产生了我遇到的问题:

from scipy import log1p, exp
from numpy import array, isnan

a = array([0.2222, 500.3, 0.3, 700.8, 0.111])

values = log1p(-exp(-exp(10**a - 9**a)))

print values # Note the nan's

indOverflow = isnan(values)
values[indOverflow] = 0

请注意我最后是如何“手动”解决问题的,但是 I/O 中发生的是:

Warning: overflow encountered in power
Warning: overflow encountered in power
Warning: invalid value encountered in subtract

我在循环中进行这种计算,所以我想将这些消息静音(因为它们已经修复,而且它们需要很多时间来打印)

最佳答案

您可以通过 numpy.seterr(over='ignore') 消除溢出警告,参见 http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

关于python - 如何检查数字溢出而不在 Python 中收到警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349434/

相关文章:

python - 我应该在 Python 3.x 的 if 语句中使用 'in' 还是 'or' 来根据多个值检查变量?

python - 输入地标或如果不匹配 foo 字符串

python - 线性回归预测与训练数据不匹配

python - 连接两个网格及其结果数组的 numpy 方法

css - 如何在不指定宽度的情况下将 html 表格保持在同一行?

python - Pygame 可以在 64 位 Python 2.7 上运行吗?

python - 从数据帧列中拆分混合数字字符串并将其转换为 float

python - 从 2D numpy 数组中删除运行

css - Firefox 只打印第一页并剪切右边的页面

C++ 整数乘法 : explain this behaviour