gpt4 book ai didi

python:绕过零除

转载 作者:IT老高 更新时间:2023-10-28 20:56:58 25 4
gpt4 key购买 nike

我有一个 float 的大数据集。我遍历它们并为它们中的每一个评估 np.log(x)。我明白了

RuntimeWarning: divide by zero encountered in log

如果发生此错误,我想解决这个问题并返回 0。

我正在考虑定义一个新函数:

def safe_ln(x):
#returns: ln(x) but replaces -inf with 0
l = np.log(x)
#if l = -inf:
l = 0
return l

基本上,我需要一种测试输出是否为 -inf 的方法,但我不知道如何继续。感谢您的帮助!

最佳答案

您正在使用 np 函数,所以我可以肯定地猜测您正在处理 numpy 数组?那么最有效的方法是使用 where 函数而不是 for 循环

myarray= np.random.randint(10,size=10)
result = np.where(myarray>0, np.log(myarray), 0)

否则你可以简单地使用日志功能,然后修补漏洞:

myarray= np.random.randint(10,size=10)
result = np.log(myarray)
result[result==-np.inf]=0

np.log 函数在值 0 时正确返回 -inf,所以您确定要返回 0 吗?如果您必须在某个地方恢复到原始值,您将遇到一些问题,将零变为一...

关于python:绕过零除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13497891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com