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

mat*_*asq 4 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
Run Code Online (Sandbox Code Playgroud)

我的问题是I/O爆炸了"警告".我知道它警告我很好,但我明确地照顾它,所以我想让它们沉默.请注意,我不想让所有类型的"溢出"警告静音,只有这里的警告.我认为像这样的东西会起作用,但它没有:

try:
   values = ExpressionThatOverFlows()
except Warning:
   pass
# and the rest of the code as it is
Run Code Online (Sandbox Code Playgroud)

我已经检查了一下,但我似乎只是找到了如何在整个会话或永远保持这些警告,但这是因为我指出的不是我想要的.

谢谢你的帮助,非常感谢.

编辑:这里有一个小得多的代码,产生我的问题:

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
Run Code Online (Sandbox Code Playgroud)

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

Warning: overflow encountered in power
Warning: overflow encountered in power
Warning: invalid value encountered in subtract
Run Code Online (Sandbox Code Playgroud)

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

pv.*_*pv. 5

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

  • 您可以使用with语句:http://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html#numpy.errstate (3认同)
  • 你可以做`oldr = numpy.seterr(over ='ignore'); 尝试:func(); 最后:numpy.seterr(**oldr)` (2认同)