在NumPy中忽略除以0警告

2024-04-29 10:52:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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
                )

有时我会从外壳上得到以下警告:

RuntimeWarning: divide by zero encountered in...

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

有没有办法忽略这条信息? 换句话说,我不希望shell打印此消息。

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


Tags: 函数fromimport功能numpy警告asnp
2条回答

可以用^{}禁用警告。把这个放在可能被零除的前面:

np.seterr(divide='ignore')

这将在全球范围内禁用零分区警告。如果只想稍微禁用它们,可以在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.

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

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

相关问题 更多 >