prevent division by zero numpy

Solutions on MaxInterview for prevent division by zero numpy by the best coders in the world

showing results for - "prevent division by zero numpy"
Lina
30 Mar 2017
1>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
2>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
3
4# If you don't pass `out` the indices where (b == 0) will be uninitialized!
5>>> c = np.divide(a, b, out=np.zeros(a.shape, dtype=float), where=b!=0)
6>>> print(c)
7[ 0.   0.   0.   1.   1.5]
8
Fern
25 Apr 2018
1>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
2>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
3
4# If you don't pass `out` the indices where (b == 0) will be uninitialized!
5>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
6>>> print(c)
7[ 0.   0.   0.   1.   1.5]