考虑以下数字的 numpy 向量:
a = np.array([.1, .2, .2, .2, .2, .1])
显然,这些数字的总和为 1。但是,当计算
b = np.sum(a)
我明白了
print (b)
0.9999999999999999
你能解释一下为什么以及如何解决这个近似问题吗?
考虑以下数字的 numpy 向量:
a = np.array([.1, .2, .2, .2, .2, .1])
显然,这些数字的总和为 1。但是,当计算
b = np.sum(a)
我明白了
print (b)
0.9999999999999999
你能解释一下为什么以及如何解决这个近似问题吗?
这是由于机器浮点精度造成的。这里详细解释:https ://docs.python.org/3/tutorial/floatingpoint.html
您可以使用以下方法修复它:
b = round(np.sum(a),5)
print(b)
您可以选择不同的数据类型来更改精度:
n = 1000
print(abs(1 - np.array([1 / n] * n).sum(dtype='float32')))
print(abs(1 - np.array([1 / n] * n).sum(dtype='float64')))
print(abs(1 - np.array([1 / n] * n).sum(dtype='float128')))
将产生:
1.1920928955078125e-07
4.440892098500626e-16
2.0816681711721685133e-17