Is numpy.sum implemented in such a way that numerical errors are avoided?

こ雲淡風輕ζ 提交于 2019-12-04 05:06:19
hpaulj

Searching on numpy kahan turned up a closed bug/issue

https://github.com/numpy/numpy/issues/2448 Numerical-stable sum (similar to math.fsum)

I haven't read it in detail. Note the reference to 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

And a SO question, with some discussion, but no real answer:

Is there any documentation of numpy numerical stability?

A simple comparison:

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

respective times are 72 ms, 304 µs, 23.8 ms

np.sum is clearly fastest; but fsum is better than sum, probably because of its sepecialized C implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!