Jul*_*lia 18 python numpy division
我有一个大的浮点数数据集.我遍历它们并评估它们np.log(x)中的每一个.我明白了
RuntimeWarning: divide by zero encountered in log
Run Code Online (Sandbox Code Playgroud)
如果发生此错误,我想解决此问题并返回0.
我正在考虑定义一个新函数:
def safe_ln(x):
#returns: ln(x) but replaces -inf with 0
l = np.log(x)
#if l = -inf:
l = 0
return l
Run Code Online (Sandbox Code Playgroud)
基本上,我需要一种测试输出的方法,-inf但我不知道如何继续.谢谢您的帮助!
Enr*_*eri 32
您正在使用np函数,所以我可以安全地猜测您正在使用numpy数组?然后,最有效的方法是使用where函数而不是for循环
myarray= np.random.randint(10,size=10)
result = np.where(myarray>0, np.log(myarray), 0)
Run Code Online (Sandbox Code Playgroud)
否则你可以简单地使用日志功能然后修补漏洞:
myarray= np.random.randint(10,size=10)
result = np.log(myarray)
result[result==-np.inf]=0
Run Code Online (Sandbox Code Playgroud)
np.log函数在值0时正确返回-inf,所以你确定要返回0吗?如果某个地方你必须恢复到原始值,你将遇到一些问题,将零改为1 ...
Con*_*ius 23
因为logfor x=0是无限的,我只是检查输入值是否为零并返回你想要的任何东西:
def safe_ln(x):
if x <= 0:
return 0
return math.log(x)
Run Code Online (Sandbox Code Playgroud)
编辑:小编辑:你应该检查所有小于或等于0的值.
编辑2:np.log当然是一个在numpy数组上计算的函数,对于你应该使用的单个值math.log.这是上面的函数看起来像numpy:
def safe_ln(x, minval=0.0000000001):
return np.log(x.clip(min=minval))
Run Code Online (Sandbox Code Playgroud)