Home > Net >  Catching 'division by zero' in a function with array parameters
Catching 'division by zero' in a function with array parameters

Time:10-27

I pass an array of values as arguments to a function. This function divides somewhere by the values given as arguments. I want to bypass the calculation for zero-value values so that I don't have to divide by zero.

import numpy as np

def test(t):
    e = np.where(t==0,0,10/t)
    return e

i = np.arange(0, 5, 1)
print('in: ',i)

o = test(i)
print('out:',o)

Output is

in:  [0 1 2 3 4]
out: [ 0.         10.          5.          3.33333333  2.5       ]

<ipython-input-50-321938d419be>:4: RuntimeWarning: divide by zero encountered in true_divide
  e = np.where(t==0,0,10/t)

I thought np.where would be the appropriate function for this, but unfortunately I always get a runtime warning 'divide by zero'. So, it does the right thing, but the warning is annoying. I could of course suppress the warning, but I wonder if there is a cleaner solution to the problem?

CodePudding user response:

Use np.divide(10, t, where=t!=0):

import numpy as np

def test(t):
    e = np.divide(10, i, where=i!=0)
    return e

i = np.arange(0, 5, 1)
print('in: ',i)

o = test(i)
print('out:',o)

CodePudding user response:

Yes, you can test if the divisor is zero, like you do but consider testing if it is equal to a floating point zero 0.0 , or otherwise provide floating point arguments.

Change test

def test(t):
    e = np.where(t==0.0,0,10.0/t) # Note : t == 0.0 (a float comparison)
    return e

And/or use floating point arguments:

i = np.arange(0., 5., 1.)

Will give you the result with out an exception too.

  • Related