python: getting around division by zero

前端 未结 7 2440
忘了有多久
忘了有多久 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条回答
  •  猫巷女王i
    2020-12-09 04:19

    I like to use sys.float_info.min as follows:

    >>> import numpy as np
    >>> import sys
    >>> arr = np.linspace(0.0, 1.0, 3)
    >>> print(arr)
    [0.  0.5 1. ]
    >>> arr[arr < sys.float_info.min] = sys.float_info.min
    >>> print(arr)
    [2.22507386e-308 5.00000000e-001 1.00000000e+000]
    >>> np.log10(arr)
    array([-3.07652656e+02, -3.01029996e-01,  0.00000000e+00])
    

    Other answers have also introduced introduced small positive values, but I prefer to use the smallest valid input when I am approximating the result for an input that is too small to be processed.

提交回复
热议问题