Notes|Python error handling|numpy warning RuntimeWarning divide by zero shielding method

When executing the following code, numpy will give RuntimeWarninga warning , and get infthe division result of

>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([3, 2, 0])
>>> a / b
<input>:1: RuntimeWarning: divide by zero encountered in true_divide
array([0.33333333, 1.        ,        inf])

This warning is due to the fact that the division by 0 exists between the two vectors performing the division. If what we expect is to get infafter , then we can use the following method to modify the numpy warning configuration to shield the warning:

>>> np.seterr(divide="ignore")
{
    
    'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
>>> a / b
array([0.33333333, 1.        ,        inf])

Guess you like

Origin blog.csdn.net/Changxing_J/article/details/129780112