python – RuntimeWarning: divide by zero encountered in log

python – RuntimeWarning: divide by zero encountered in log

numpy.log10(prob) calculates the base 10 logarithm for all elements of prob, even the ones that arent selected by the where. If you want, you can fill the zeros of prob with 10**-10 or some dummy value before taking the logarithm to get rid of the problem. (Make sure you dont compute prob > 0.0000000001 with dummy values, though.)

You can turn it off with seterr

numpy.seterr(divide = ignore) 

and back on with

numpy.seterr(divide = warn) 

python – RuntimeWarning: divide by zero encountered in log

Just use the where argument in np.log10

import numpy as np
np.random.seed(0)

prob = np.random.randint(5, size=4) /4
print(prob)

result = np.where(prob > 0.0000000001, prob, -10)
# print(result)
np.log10(result, out=result, where=result > 0)
print(result)

Output

[1.   0.   0.75 0.75]
[  0.         -10.          -0.12493874  -0.12493874]

Leave a Reply

Your email address will not be published.