我有一个表达式,它会因某些参数值而溢出。在这种情况下,我已经使用笔和纸得出了渐近结果应该是什么,当我遇到这种情况时,我只是用我的解析表达式替换。
目前我的代码是这样的:
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/