How to Return 0 with Divide by Zero

How to return 0 with divide by zero

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.

How to return 0 with divide by 0 from string?

you can try

try:
#Your operation here
except ZeroDivisionError:
# return 0 here

More information here: https://en.wikibooks.org/wiki/Python_Programming/Exceptions

Make division by zero equal to zero

Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.

def weird_division(n, d):
return n / d if d else 0

How to avoid the divide by zero error in SQL?

In order to avoid a "Division by zero" error we have programmed it like this:

Select Case when divisor=0 then null
Else dividend / divisor
End ,,,

But here is a much nicer way of doing it:

Select dividend / NULLIF(divisor, 0) ...

Now the only problem is to remember the NullIf bit, if I use the "/" key.

Divide by zero warning when using np.choose

The Problem

Unfortunately, the popular NumPy function np.choose() does not allow for conditional execution (neither does np.where(), btw). Since the Python function parameters are evaluated in their entirety before the function call, they cannot be conditionally evaluated for a subset of its parameters. In turn, a RuntimeWarning about the division of zero is provided although you tried to make sure this does not happen.

The Solution

I would replace np.choose() with the NumPy function for element-wise division. np.divide() allows the specification of a condition that must be met for division (namely that the element is non-zero a!=0) through the where argument. In turn, no runtime error is thrown. More generally, the where argument can be provided to any NumPy function that operates element by element on a given array, so-called ufuncs. Where the condition is not met, the array a will retain its original value, i.e. 0 in your case.

Additionaly, I'd leverage np.where() to count (non-)zero entries.

a = np.array([[0., 1., 2., 3.], [10., 11., 0., 13.], [20., 21., 22., 23.], [0., 31., 32., 33.]])

ycmpnt = np.divide(a+1, a, out=np.zeros_like(a), where=a!=0)
count = np.where(a!=0, 0, 1)

Note that np.abs(a)>0 should be replaced with the algebraically equivalently but faster a!=0.



Related Topics



Leave a reply



Submit