gpt4 book ai didi

python - 在 np.where() 上的 true_divide 中遇到 Numpy 除以零

转载 作者:行者123 更新时间:2023-12-05 03:47:47 28 4
gpt4 key购买 nike

当我得到试图避免被零除的 np.where 时,我仍然收到错误,即使 p_arr - 0.5 应该始终是 > 0

mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

RuntimeWarning: divide by zero encountered in true_divide

mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

知道为什么以及如何解决这个问题吗?此外,有什么方法可以正确调试它,以便错误显示 p_arr 的确切值是多少?

一些测试:

x = np.where(p_arr > 0.5, p_arr, 1)
print(np.all((p_arr - 0.5 != 0))) # FALSE
print(np.all((x - 0.5 != 0))) # TRUE

最佳答案

np.where 的伪代码:

def np_where(chooser, true_opt, false_opt):
out = np.empty(chooser.shape, dtype = true_opt.dtype)
out[~chooser] = false_opt
return out

重要的是,true_opt 是在 调用该函数之前生成的。因此,如果其中的任何内容引发错误,解释器永远不会调用 np.where - 即使 np.where 永远不会使用 true_opt

您可以消除 除以零 错误,但不要按照其他答案中的建议使用 np.seterr - 这将关闭它整个 session ,并可能导致其他代码出现问题。你可以这样做:

with np.errstate(divide='ignore'):
mo = np.where(p_arr > 0.5, -6.93/(p_arr - 0.5), 10)

要找出错误的来源,只需使用:

np.where(p_arr == 0.5)

它应该为您提供发生除以零错误的坐标

关于python - 在 np.where() 上的 true_divide 中遇到 Numpy 除以零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64747346/

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