Nic*_*man 7 python precision numpy numerical-methods
众所周知,累加数字会导致数字错误(例如,如果第一个数字非常大,而有许多其他小数字).
这可以通过非直接的方式将数字相加来解决.例如,参见:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum是否以避免数值错误的方式实现?
搜索出现numpy kahan了一个已关闭的错误/问题
https://github.com/numpy/numpy/issues/2448 Numerical-stable sum(类似于 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
Run Code Online (Sandbox Code Playgroud)
还有一个 SO 问题,经过一些讨论,但没有真正的答案:
简单对比:
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
Run Code Online (Sandbox Code Playgroud)
分别为 72 ms、304 µs、23.8 ms
np.sum显然是最快的;但fsum比 好sum,可能是因为它的特殊 C 实现。