Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise error for nan value in python numpy

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.

like image 480
Šimon Brecher Avatar asked Feb 17 '26 16:02

Šimon Brecher


1 Answers

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
like image 198
juanpa.arrivillaga Avatar answered Feb 20 '26 04:02

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!