Python:绕过零除 [英] python: getting around division by zero
问题描述
我有一个很大的浮点数数据集.我遍历它们并为每个评估np.log(x)
.
我知道了
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
我想解决这个问题,如果发生此错误,则返回0.
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
基本上,我需要一种测试输出是否为-inf
的方法,但我不知道如何进行.
谢谢您的帮助!
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!
推荐答案
由于x=0
的log
为负无穷大,因此我只需要检查输入值是否为零并返回您想要的值即可:>
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)
编辑:小修改:您应检查所有小于或等于0的值.
EDIT: small edit: you should check for all values smaller than or equal to 0.
编辑2 :np.log
当然是在numpy数组上计算的函数,对于单个值,应使用math.log
.这就是上面的函数与numpy的外观:
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))
这篇关于Python:绕过零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!