python 忽略警告继续运行程序_在NumPy中忽略除以0的警告

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:

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.

Is there a way to ignore the message?

In other words, I do not want the shell to print this message.

I do not want to disable all python warnings, just this one.

解决方案

You can disable the warning with numpy.seterr. Put this before the possible division by zero:

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:

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".

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值