python: getting around division by zero

前端 未结 7 2438
忘了有多久
忘了有多久 2020-12-09 03:38

I have a big data set of floating point numbers. I iterate through them and evaluate np.log(x) for each of them. I get

RuntimeWarning: divide b         


        
7条回答
  •  青春惊慌失措
    2020-12-09 04:00

    The answer given by Enrico is nice, but both solutions result in a warning:

    RuntimeWarning: divide by zero encountered in log
    

    As an alternative, we can still use the where function but only execute the main computation where it is appropriate:

    # alternative implementation -- a bit more typing but avoids warnings.
    loc = np.where(myarray>0)
    result2 = np.zeros_like(myarray, dtype=float)
    result2[loc] =np.log(myarray[loc])
    
    # answer from Enrico...
    myarray= np.random.randint(10,size=10)
    result = np.where(myarray>0, np.log(myarray), 0)
    
    # check it is giving right solution:
    print(np.allclose(result, result2))
    

    My use case was for division, but the principle is clearly the same:

    x = np.random.randint(10, size=10)
    divisor = np.ones(10,)
    divisor[3] = 0 # make one divisor invalid
    
    y = np.zeros_like(divisor, dtype=float)
    loc = np.where(divisor>0) # (or !=0 if your data could have -ve values)
    y[loc] = x[loc] / divisor[loc]
    

提交回复
热议问题