【发布时间】:2016-01-05 09:09:16
【问题描述】:
众所周知,将数字相加会导致数字错误(例如,如果第一个数字非常大,而其他小数字很多)。
这可以通过一种非直接的方式将数字相加来解决。例如:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum 是否以避免数值错误的方式实现?
【问题讨论】:
标签: python numpy precision numerical-methods
众所周知,将数字相加会导致数字错误(例如,如果第一个数字非常大,而其他小数字很多)。
这可以通过一种非直接的方式将数字相加来解决。例如:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum 是否以避免数值错误的方式实现?
【问题讨论】:
标签: python numpy precision numerical-methods
在 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 实现。
【讨论】: