python: getting around division by zero

前端 未结 7 2445
忘了有多久
忘了有多久 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:14

    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))
    

提交回复
热议问题