I need to automatically raise an error, if I divide by zero in numpy array using the "/" operator, or better if I do any operation, that results in nan.
What numpy does instead is to return nan value. I do not need my program to run after that, since there is obviously a mistake.
I want a way to know when division by zero is used and on which line. Just forbid any value of nan to be even created.
The default behavior is to emit a warning, but you can set the behavior using np.seterr:
>>> import numpy as np
>>> np.array([1,2,3]) / np.array([0, 1, 2])
__main__:1: RuntimeWarning: divide by zero encountered in true_divide
array([inf, 2. , 1.5])
After we change it to "raise":
>>> np.seterr(divide='raise')
{'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
>>> np.array([1,2,3]) / np.array([0, 1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FloatingPointError: divide by zero encountered in true_divide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With