How to return 0 with divide by zero
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs
--
Chapters
00:00 Question
00:59 Accepted answer (Score 315)
01:37 Answer 2 (Score 57)
02:01 Answer 3 (Score 52)
02:40 Answer 4 (Score 20)
02:56 Thank you
--
Full question
https://stackoverflow.com/questions/2624...
Question links:
[numpy.seterr()]: http://docs.scipy.org/doc/numpy/referenc...
Accepted answer links:
[ufuncs]: http://docs.scipy.org/doc/numpy/referenc...
Answer 3 links:
[numpy.errstate()]: http://docs.scipy.org/doc/numpy/referenc...
[numpy.nan_to_num()]: http://docs.scipy.org/doc/numpy/referenc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #numpy #errorhandling #dividebyzero
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs
--
Chapters
00:00 Question
00:59 Accepted answer (Score 315)
01:37 Answer 2 (Score 57)
02:01 Answer 3 (Score 52)
02:40 Answer 4 (Score 20)
02:56 Thank you
--
Full question
https://stackoverflow.com/questions/2624...
Question links:
[numpy.seterr()]: http://docs.scipy.org/doc/numpy/referenc...
Accepted answer links:
[ufuncs]: http://docs.scipy.org/doc/numpy/referenc...
Answer 3 links:
[numpy.errstate()]: http://docs.scipy.org/doc/numpy/referenc...
[numpy.nan_to_num()]: http://docs.scipy.org/doc/numpy/referenc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #numpy #errorhandling #dividebyzero
#avk47
ACCEPTED ANSWER
Score 352
In numpy v1.7+, you can take advantage of the "where" option for ufuncs. You can do things in one line and you don't have to deal with the errstate context manager.
>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0. 0. 0. 1. 1.5]
In this case, it does the divide calculation anywhere 'where' b does not equal zero. When b does equal zero, then it remains unchanged from whatever value you originally gave it in the 'out' argument.
ANSWER 2
Score 57
Building on @Franck Dernoncourt's answer, fixing -1 / 0 and my bug on scalars:
def div0( a, b, fill=np.nan ):
""" a / b, divide by 0 -> `fill`
div0( [-1, 0, 1], 0, fill=np.nan) -> [nan nan nan]
div0( 1, 0, fill=np.inf ) -> inf
"""
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide( a, b )
if np.isscalar( c ):
return c if np.isfinite( c ) \
else fill
else:
c[ ~ np.isfinite( c )] = fill
return c
ANSWER 3
Score 54
Building on the other answers, and improving on:
0/0handling by addinginvalid='ignore'tonumpy.errstate()- introducing
numpy.nan_to_num()to convertnp.nanto0.
Code:
import numpy as np
a = np.array([0,0,1,1,2], dtype='float')
b = np.array([0,1,0,1,3], dtype='float')
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a,b)
c[c == np.inf] = 0
c = np.nan_to_num(c)
print('c: {0}'.format(c))
Output:
c: [ 0. 0. 0. 1. 0.66666667]
ANSWER 4
Score 17
Try doing it in two steps. Division first, then replace.
with numpy.errstate(divide='ignore'):
result = numerator / denominator
result[denominator == 0] = 0
The numpy.errstate line is optional, and just prevents numpy from telling you about the "error" of dividing by zero, since you're already intending to do so, and handling that case.