关于python:在NumPy中忽略除以0的警告

Ignore divide by 0 warning in NumPy

我有一个统计问题的功能:

1
2
3
4
5
6
7
8
9
10
11
12
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
                )

有时我会从外壳中收到以下警告:

1
RuntimeWarning: divide by zero encountered in...

我使用numpy isinf函数更正其他文件中的函数结果,因此不需要此警告。

有没有办法忽略该消息?
换句话说,我不希望外壳程序打印此消息。

我不想禁用所有python警告,仅禁用这一警告。


您可以使用numpy.seterr禁用警告。 将其放在可能除以零之前:

1
np.seterr(divide='ignore')

这将全局禁用零除警告。 如果只想禁用它们一点,可以在with子句中使用numpy.errstate

1
2
with np.errstate(divide='ignore'):
    # some code here

对于零除零除法(不确定,导致NaN),错误行为在numpy版本1.12.0中已更改:现在被视为"无效",而以前被称为"除法"。

因此,如果您的分子有可能也为零,请使用

1
np.seterr(divide='ignore', invalid='ignore')

要么

1
2
with np.errstate(divide='ignore', invalid='ignore'):
    # some code here

请参阅发行说明中的"兼容性"部分,以及"新功能"部分之前的最后一段:

Comparing NaN floating point numbers now raises the invalid runtime warning. If a NaN is expected the warning can be ignored using np.errstate.


您也可以使用numpy.divide进行除法。 这样,您不必显式禁用警告。

1
2
In [725]: np.divide(2, 0)
Out[725]: 0