gpt4 book ai didi

python - 为什么 numpy.allclose 使用非对称比较?

转载 作者:行者123 更新时间:2023-11-28 17:04:32 26 4
gpt4 key购买 nike

numpy.allclose声明为 numpy.allclose(a, b, rtol=1e-05, atol=1e-08, ...),并使用以下方法实现非对称比较:

absolute(a - b) <= (atol + rtol * absolute(b))

非对称比较的结果是 allclose(a, b) 在极少数情况下可能与 allclose(b, a) 不同,因此使得allclosecommutative ,这对于比较运算符来说是一个令人惊讶的属性。

不对称比较的原因是什么?

最佳答案

除了我的评论,math.isclose使用 abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)这是可交换的,但是以额外的操作为代价(对于需要堆叠以找到最大值的 numpy 数组来说,这可能是昂贵的)。如果您确实需要此属性,那么实现您自己的并不难:

def isclose_comm(a, b, rtol=1e-5, atol=1e-8):
ab = np.stack((a, b))
return np.abs(a - b) <= (atol + rtol * ab.max(axis=0))

x = np.random.random(5)

x
Out[94]: array([0.36007049, 0.86934972, 0.05827216, 0.60794612, 0.24539454])

y = x + np.random.random(5)/1e6

y
Out[96]: array([0.36007072, 0.86934976, 0.05827312, 0.6079464 , 0.24539492])

np.isclose(x, y)
Out[97]: array([ True, True, False, True, True])

isclose_comm(x, y)
Out[98]: array([ True, True, True, True, True])

z = np.zeros(5)

isclose_comm(x, z)
Out[100]: array([False, False, False, False, False])

allclose等价的:

def allclose_comm(a, b, rtol=1e-5, atol=1e-8):
return isclose_comm(a, b, rtol, atol).all()

关于python - 为什么 numpy.allclose 使用非对称比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51931720/

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