众所周知,添加数字可能会导致数字错误(例如,如果第一个数字非常大,而有许多其他小数字)。
这可以通过非直接的方式将数字相加来解决。例如,请参阅:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum是否以避免数值错误的方式实现?
答案 0 :(得分:3)
在numpy kahan
上搜索已发现已关闭的错误/问题
https://github.com/numpy/numpy/issues/2448数值稳定和(类似于math.fsum)
我没有详细阅读。请注意对math.fsum
fsum(iterable)
Return an accurate floating point sum of values in the iterable.
Assumes IEEE-754 floating point arithmetic.
(from the Python math docs)
Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums
还有一个问题,有一些讨论,但没有真正的答案:
Is there any documentation of numpy numerical stability?
一个简单的比较:
In [320]: x=np.ones(100000)/100000
In [321]: sum(x)-1
Out[321]: -1.9162449405030202e-12
In [322]: np.sum(x)-1
Out[322]: 1.3322676295501878e-15
In [323]: math.fsum(x)-1
Out[323]: 0.0
各个时间是72毫秒,304微秒,23.8毫秒
np.sum
显然最快;但fsum
优于sum
,可能是因为其专有的C实现。