Python 忽略 NumPy 中的除以 0 警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29950557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ignore divide by 0 warning in NumPy
提问by overcomer
I have a function for statistic issues:
我有一个统计问题的功能:
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
)
Sometimes I get from the shell the following warning:
有时我会从 shell 收到以下警告:
RuntimeWarning: divide by zero encountered in...
I use the numpy isinf
function to correct the results of the function in other files, so I do not need this warning.
我使用numpyisinf
函数来修正其他文件中函数的结果,所以我不需要这个警告。
Is there a way to ignore the message? In other words, I do not want the shell to print this message.
有没有办法忽略消息?换句话说,我不希望 shell 打印此消息。
I do not want to disable all python warnings, just this one.
我不想禁用所有 python 警告,只是这个。
采纳答案by dddsnn
You can disable the warning with numpy.seterr
. Put this before the possible division by zero:
您可以使用 禁用警告numpy.seterr
。把它放在可能被零除之前:
np.seterr(divide='ignore')
That'll disable zero division warnings globally. If you just want to disable them for a little bit, you can use numpy.errstate
in a with
clause:
这将在全球范围内禁用零除法警告。如果您只是想暂时禁用它们,可以numpy.errstate
在with
子句中使用:
with np.errstate(divide='ignore'):
# some code here
For a zero by zero division (undetermined, results in a NaN), the error behaviour has changed with numpy version 1.12.0: this is now considered "invalid", while previously it was "divide".
对于零除以零(未确定,导致 NaN),错误行为在 numpy 版本 1.12.0 中发生了变化:现在被认为是“无效”,而以前是“除法”。
Thus, if there is a chance you your numerator could be zero as well, use
因此,如果您的分子也有可能为零,请使用
np.seterr(divide='ignore', invalid='ignore')
or
或者
with np.errstate(divide='ignore', invalid='ignore'):
# some code here
See the "Compatibility" section in the release notes, last paragraph before the "New Features" section:
请参阅发行说明中的“兼容性”部分, “新功能”部分之前的最后一段:
Comparing NaN floating point numbers now raises the invalid runtime warning. If a NaN is expected the warning can be ignored using np.errstate.
比较 NaN 浮点数现在会引发无效运行时警告。如果预期为 NaN,则可以使用 np.errstate 忽略警告。
回答by fixxxer
You could also use numpy.divide
for division. That way you don't have to explicitly disable warnings.
您也可以numpy.divide
用于除法。这样您就不必明确禁用警告。
In [725]: np.divide(2, 0)
Out[725]: 0