众所周知,将数字相加会导致数字错误(例如,如果第一个数字非常大,而其他许多数字都较小)。
这可以通过非直接的方式将数字相加来解决。参见示例: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
还有一个 SO 问题,有一些讨论,但没有真正的答案:
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 ms、304 µs、23.8 ms
np.sum
显然是最快的;但是 fsum
比 sum
好,可能是因为它的特殊 C 实现。
关于python - numpy.sum 的实现方式是否避免了数值错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33004029/