To add a little @Bakuriu answer:
If you already know where the warning may occur, it is better to use the numpy.errstate context manager, rather than numpy.seterr which processes all subsequent warnings of the same type, regardless of where they appear in your code:
import numpy as np a = np.r_[1.] with np.errstate(divide='raise'): try: a / 0
Edit:
In my original example, I had a = np.r_[0] , but apparently there was a change in the behavior of numpy, so division by zero is handled differently when the numerator is all zeros. For example, in numpy 1.16.4:
all_zeros = np.array([0., 0.]) not_all_zeros = np.array([1., 0.]) with np.errstate(divide='raise'): not_all_zeros / 0.
Relevant warning messages also vary: 1./0. registered as RuntimeWarning: divide by zero encountered in true_divide , whereas 0./0. registered as RuntimeWarning: invalid value encountered in true_divide . I'm not sure why this change was made, but I suspect that this is due to the fact that the result is 0./0. cannot be represented as a number (numpy returns NaN in this case), whereas 1./0. and -1./0. -1./0. return + Inf and -Inf, respectively, in accordance with the IEE 754 standard.
If you want to catch both types of errors, you can always pass np.errstate(divide='raise', invalid='raise') or all='raise' if you want to throw an exception for any type of floating point error,
ali_m Nov 13 '15 at 21:21 2015-11-13 21:21
source share