Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 0 with divide by zero

People also ask

How do you solve a divide by zero error?

Use IFERROR to suppress the #DIV/0! error. You can also suppress this error by nesting your division operation inside the IFERROR function. Again, using A2/A3, you can use =IFERROR(A2/A3,0).

How do you get a zero in division?

A Number Divided by 1 a1=a Just like multiplying by 1, dividing any number by 1 doesn't change the number at all. 0 Divided by a Number 0a=0 Dividing 0 by any number gives us a zero.

How do I allow division by 0 in Python?

In Python, we use a try block that contains a return statement to divide 2 numbers. If there is no division by zero error, then it will return the result. Otherwise, the except line will check if the specified exception name is a match, and then it will execute the code under the except block.

How does Numpy divide by zero?

Behavior on division by zero can be changed using seterr. When both x1 and x2 are of an integer type, divide will return integers and throw away the fractional part. Moreover, division by zero always yields zero in integer arithmetic.


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.


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

Building on the other answers, and improving on:

  • 0/0 handling by adding invalid='ignore' to numpy.errstate()
  • introducing numpy.nan_to_num() to convert np.nan to 0.

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]

DEPRECATED (PYTHON 2 SOLUTION):

One-liner (throws warning)

np.nan_to_num(array1 / array2)