我有一个统计问题的函数:
import numpy as np
from scipy.special import gamma as Gamma
def Foo(xdata):
...
return x1 * (
( #R is a numpy vector
( ((R - x2)/beta) ** (x3 -1) ) *
( np.exp( - ((R - x2) / x4) ) ) /
( x4 * Gamma(x3))
).real
)
有时我会从 shell 收到以下警告:
RuntimeWarning: divide by zero encountered in...
我使用 numpy isinf
函数来更正其他文件中函数的结果,所以我不需要这个警告。
有没有办法忽略该消息? 换句话说,我不希望 shell 打印这条消息。
我不想禁用所有 python 警告,只是这个。
最佳答案
您可以使用 numpy.seterr
禁用警告。 .把它放在可能被零除之前:
np.seterr(divide='ignore')
这将在全局范围内禁用零除法警告。如果您只是想暂时禁用它们,可以使用 numpy.errstate
在 with
子句中:
with np.errstate(divide='ignore'):
# some code here
对于零除零(未确定,导致 NaN),错误行为在 numpy 版本 1.12.0 中发生了变化:现在被认为是“无效”,而之前是“除法”。
因此,如果您的分子也有可能为零,请使用
np.seterr(divide='ignore', invalid='ignore')
或
with np.errstate(divide='ignore', invalid='ignore'):
# some code here
参见 release notes 中的“兼容性”部分,“新功能”部分之前的最后一段:
Comparing NaN floating point numbers now raises the invalid runtime warning. If a NaN is expected the warning can be ignored using np.errstate.
关于python - 在 NumPy 中忽略除以 0 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950557/