python: getting around division by zero

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

    use exception handling:

    In [27]: def safe_ln(x):
        try:
            return math.log(x)
        except ValueError:       # np.log(x) might raise some other error though
            return float("-inf")
       ....:     
    
    In [28]: safe_ln(0)
    Out[28]: -inf
    
    In [29]: safe_ln(1)
    Out[29]: 0.0
    
    In [30]: safe_ln(-100)
    Out[30]: -inf
    

提交回复
热议问题