Search code examples
pythonnumpydivision

python: getting around division by zero


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 by zero encountered in log

I would like to get around this and return 0 if this error occurs.

I am thinking of defining a new function:

def safe_ln(x):
    #returns: ln(x) but replaces -inf with 0
    l = np.log(x)
    #if l = -inf:
    l = 0
    return l

Basically,I need a way of testing that the output is -inf but I don't know how to proceed. Thank you for your help!


Solution

  • Since the log for x=0 is minus infinite, I'd simply check if the input value is zero and return whatever you want there:

    def safe_ln(x):
        if x <= 0:
            return 0
        return math.log(x)
    

    EDIT: small edit: you should check for all values smaller than or equal to 0.

    EDIT 2: np.log is of course a function to calculate on a numpy array, for single values you should use math.log. This is how the above function looks with numpy:

    def safe_ln(x, minval=0.0000000001):
        return np.log(x.clip(min=minval))