5
衆所周知,合計數字會導致數字錯誤(例如,如果第一個數字非常大,而其他許多小數字)。numpy.sum是否以避免數值錯誤的方式實現?
這可以通過以非直接方式累加數字來解決。請參閱:https://en.wikipedia.org/wiki/Kahan_summation_algorithm
numpy.sum是否以避免數值錯誤的方式實現?
衆所周知,合計數字會導致數字錯誤(例如,如果第一個數字非常大,而其他許多小數字)。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
而一個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實現。