numpy.sum是否以避免数字错误的方式实现? [英] Is numpy.sum implemented in such a way that numerical errors are avoided?

查看:82
本文介绍了numpy.sum是否以避免数字错误的方式实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,将数字相加会导致数字错误(例如,如果第一个数字确实很大,而还有许多其他小数字).

It is well known that adding up numbers can result in numerical errors (for example, if the first number is really large, whereas there are many other small numbers).

这可以通过非直截了当的方式将数字相加来解决.例如,请参见: https://en.wikipedia.org/wiki/Kahan_summation_algorithm

This can be solved adding up the numbers in a non straight-forward way. See for example: https://en.wikipedia.org/wiki/Kahan_summation_algorithm

numpy.sum是否以避免数字错误的方式实现?

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

推荐答案

numpy kahan上搜索发现了已关闭的bug/问题

Searching on numpy kahan turned up a closed bug/issue

https://github.com/numpy/numpy/issues/2448 数值稳定的总和(类似于math.fsum)

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

我没有详细阅读.请注意对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

还有一个SO问题,经过一些讨论,但没有真正的答案:

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

是否有任何有关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 ms,304 µs,23.8 ms

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

np.sum显然是最快的;但是fsumsum更好,这可能是因为它是C语言实现的分隔符.

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

这篇关于numpy.sum是否以避免数字错误的方式实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆