python - 在 NumPy 中忽略除以 0 警告

标签 python numpy suppress-warnings divide-by-zero

我有一个统计问题的函数:

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.errstatewith 子句中:

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/

相关文章:

c++ - 如何通过编译器命令行禁用 IBM xl C++ 编译器的特定警告?

python - Pandas 的不确定性

Python 元类与类装饰器

python - 连接列表列表中的两个字符串

python - 如何使用 `xarray.DataArray` 索引器更新 `.sel()`?

python - Python 中 Matlab 的 'fread' 是什么?

python - Django 形成 HTML5 验证模式

python - 使用 NumPy 获取反向累积密度函数?

C# 禁用警告

c# - 我该如何修复 SCS0028?