众所周知,对数字进行累加可能会导致数值误差(例如,如果第一个数字非常大,而其他数字非常小)。
可以通过以非直观的方式相加来解决这个问题。例如,请参见:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum是否实现了避免数值误差的方法?
众所周知,对数字进行累加可能会导致数值误差(例如,如果第一个数字非常大,而其他数字非常小)。
可以通过以非直观的方式相加来解决这个问题。例如,请参见:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum是否实现了避免数值误差的方法?
在搜索 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
以下是一篇关于numpy数值稳定性的问题,包含了一些讨论但没有解决方案:
下面是一个简单的比较:
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 实现。