Ignore divide by 0 warning in NumPy

旧城冷巷雨未停 提交于 2019-11-28 07:19:48

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.

You could also use numpy.divide for division. That way you don't have to explicitly disable warnings.

In [725]: np.divide(2, 0)
Out[725]: 0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!