gpt4 book ai didi

python - 点积的 numpy 机器精度?

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:20 27 4
gpt4 key购买 nike

如何处理 numpy 中的浮点精度?例如在下面的 a==0 中返回 False,即使达到机器精度它是 0:

a = -2.22044605e-16

这尤其是一个问题,因为我正在计算向量的点积,结果似乎受到了影响,即 a 被视为“负”数。

np.finfo(float).eps 

返回 -2.22044605e-16

这是一个例子:

a = np.array([[-2.22044605e-16,-2.22044605e-16]])

b = np.array([[5,5]])

np.dot(a,b)
array([[ -2.22044605e-15]])

a = np.array([[-2.22044605e-16,2.22044605e-16]])
np.dot(a,b.T)
array([[ 0.]])

最佳答案

尝试 numpy.allclose .

来自链接:

numpy.allclose(a, b, rtol=1e-05, atol=1e-08)

Returns True if two arrays are element-wise equal within a tolerance.

The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

If either array contains one or more NaNs, False is returned. Infs are treated as equal if they are in the same place and of the same sign in both arrays.


If the following equation is element-wise True, then allclose returns True:

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

示例:

>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False

所以:

而不是做:

>>> 0 == -2.22044605e-16
False

做:

>>> import numpy as np
>>> np.allclose([0], [-2.22044605e-16])
True

关于python - 点积的 numpy 机器精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644720/

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