You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
numpy.sum not stable enough sometimes (Kahan, math.fsum) #8786
To approximate an integral over the reference interval [-1, 1], one arranges points x_i and weights w_i such that the number
sum(f(x_i) * w_i)
approximates the integral of some functions f (typically a set of polynomials) reasonably well. Sophisticated schemes have many points and weights, and naturally the more weights there are, the smaller each individual weight must be.
Bottom line: You'll have to sum up many small values.
When numpy.sum doesn't cut it
I noticed that numpy.sum produces large enough round-off errors for the tests to fail with as few as 7 summands (being -44.34121805, -15.72356145, -0.04563372, 0., 0.04563372, 15.72356145, 44.34121805, not shown in full precision). math.fsum always worked fine, but cannot be used anymore since I'd like to compute the sum for many intervals at once.
sum uses pairwise summation which is reasonably accurate without a performance impact.
kahan sum could already be implemented now but is significantly slower.
how exactly are you summing? pairwise summation unfortunately is not used when you are summing along a strided axis, again for performance reasons.
Implementing an even more accurate sum is interesting, maybe via a new function or some precision context manager. Though it the use cases need to be clear. Kahan is easy to implement and acceptable in performance but not as good the algorithm math.fsum uses which is significantly slower and more complicated to implement.
Well, you can't expect much difference here, its just a few numbers after all. And you can always get catastrophic anihilation, even in pairwise summation, pairwise summation is just much better because in typical scenarios it make sure that the two numbers being added are always of similar size.
E.g. if you would restructure your numbers by always having the first, last, second, second to last, etc. you would get a good result of course (and maybe even better for pairwise).
Another quick hack to get better accuracy is to sort your array before summing.
It'd certainly be nice to have better summation algorithms available as an option, but np.sum is unlikely to ever use them by default given the performance cost.
Right, silly by me. The pairwise stuff could maybe actually have helped,since it might sum all the negative and then all the positive ones one after another (the example actually was sorted, but basically symmetric about zero, which invites anihilation)?
The same algorithm used to generate a Hamming code could also be adapted: always summing the two numbers of smallest absolute value. Could be implemented as a priority queue. I'm not recommending that, have just wondered now and then how well it would work...
Sorry, yeah, you would want to sort by absolute value. (I've only used this trick for summing probabilities, where this doesn't come up, so I forgot :-).)
A stable numpy sum would be awesome. Sorting is a PITA since you have to do it by a key (abs), and if you have a more than 1-d array you have to sort each subarray independently.
We would also like to have a more precise sum, for a likelihood that's the sum of ~ a billion numbers.
@nschloe - Very nice comparison in accupy, thanks!
So your conclusion is that the precision of kahan sum isn't much better, so not worth exposing in Numpy?
(kahan is actually already here for a different application, not for numpy.sum)
fsum accuracy seems amazing. How slow is it?
The speed comparison in accupy isn't fair since it's using a Python for loop, no?
(See here).
Is a fsum available (in C or Cython or Numba or ...) somewhere that works on Numpy arrays?
@cdeil python uses Shewchuk summation, my guess is you can just look at their code or google a C implementation at the very least. Adapting it into short cython code is probably less work then trying to dig very long.
Now that we support the axis argument for gufuncs, it could actually be a nice little exercise to implement a gufunc for stable summation. Not sure it will be ideal performance wise, but cython solution are unlikely to be any better (unless they bloat up a lot).
So your conclusion is that the precision of kahan sum isn't much better, so not worth exposing in Numpy?
Not my conclusion but a known property of Kahan. It's just not robust when it comes to ill-conditioned sums. The best thing would be have fsum (aka Shewchuk) indeed, but there are faster solutions too which work in k-fold machine precision. (See accupy.)
You can acutally try accupy though and see if it fits your needs. If yes, perhaps we can tweak it for speed.
The speed comparison in accupy isn't fair since it's using a Python for loop, no?
It does indeed. If you can get it done in C++, super!
The reason why math.fsum() and sum() now yield the same result might be that since Python 3.12 the algorithm for sum() was improved: "sum() now uses Neumaier summation to improve accuracy and commutativity when summing floats or mixed ints and floats. ", see docs.python.org/3/whatsnew/3.12.html
I am not sure whether I should open a new issue or not. Please let me know.
Issue:
In the following example, I've created two 1D numpy arrays. Both have the same non-zero elements but at different positions. They have different sum !
Example:
import numpy as np
non_zero_elems = """
0.024861743494183196 0.024861743494183196 0.024861743494183196
0.021792470064670937 0.021792470064670937 0.018949939845733486
0.018949939845733486 0.0015757541842979532 0.0015757541842979532
0.0015757541842979532 0.0015757541842979532 0.0015757541842979532
0.0015757541842979532 0.0015757541842979532 0.0015757541842979532
0.04033997886552635 0.04033997886552635 0.04033997886552635
0.04033997886552635
"""
non_zero_elems = np.array(non_zero_elems.split()).astype(np.float64)
IDX1 = np.array([28, 29, 30, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54])
IDX2 = np.array([ 8, 9, 10, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54])
# `x` and `y` are two arrays with the same non-zero elements but at different positions
x = np.zeros(55, dtype=np.float64)
y = np.zeros(55, dtype=np.float64)
x[IDX1] = non_zero_elems.copy()
y[IDX2] = non_zero_elems.copy()
print(np.sum(x) == np.sum(y)) # False!!
print(np.sum(x[x!=0]) == np.sum(y[y!=0])) # True
In the following example, I've created two 1D numpy arrays. Both have the same non-zero elements but at different positions. They have different sum !
It's not an issue, it is a basic property of numerical floating point math that re-ordering even the simplest operations can lead to different results. More stable summation may do that less, but I don't think there is any reasonable version that is completely exact.
Well, I think there is nothing to do about mean/sum directly. We could think about a new function or maybe about a new option to sum/mean (but that is harder).
So I think it's a reasonable request, but a hard one. A new function would be the simplest thing probably.
(I don't see anything to do about documentation.)
Activity
eric-wieser commentedon Mar 15, 2017
I don't think that
copyis needed there.These seems like an improvement that could be built directly in to the
sumfunction if #8773 were implementedjuliantaylor commentedon Mar 15, 2017
sum uses pairwise summation which is reasonably accurate without a performance impact.
kahan sum could already be implemented now but is significantly slower.
how exactly are you summing? pairwise summation unfortunately is not used when you are summing along a strided axis, again for performance reasons.
Implementing an even more accurate sum is interesting, maybe via a new function or some precision context manager. Though it the use cases need to be clear. Kahan is easy to implement and acceptable in performance but not as good the algorithm math.fsum uses which is significantly slower and more complicated to implement.
nschloe commentedon Mar 15, 2017
And more precise.
Interesting. I'm using
numpy.sum(a, axis=0), so that shouldn't be a problem.juliantaylor commentedon Mar 15, 2017
That might be the problem, the fast axis in numpy is the last one by default (C order).
How does it fare when you have your arrays in fortran order?
nschloe commentedon Mar 15, 2017
When
transpose()ing and summing overaxis=-1, I see the same deficiencies.eric-wieser commentedon Mar 15, 2017
Yes, that's because you're doing exactly the same operation over memory, and just calling the axes different things
np.copy(c, order='f').sum(axis=0)is the relevent test.seberg commentedon Mar 15, 2017
You would have to sparkle in a
copythere after the transpose, or docopy("F")and not transpose.nschloe commentedon Mar 15, 2017
Thanks for the clarification. Unfortunately,
has the same lack of precision as the original statement.
seberg commentedon Mar 15, 2017
Well, you can't expect much difference here, its just a few numbers after all. And you can always get catastrophic anihilation, even in pairwise summation, pairwise summation is just much better because in typical scenarios it make sure that the two numbers being added are always of similar size.
E.g. if you would restructure your numbers by always having the first, last, second, second to last, etc. you would get a good result of course (and maybe even better for pairwise).
njsmith commentedon Mar 15, 2017
Another quick hack to get better accuracy is to sort your array before summing.
It'd certainly be nice to have better summation algorithms available as an option, but
np.sumis unlikely to ever use them by default given the performance cost.seberg commentedon Mar 15, 2017
Right, silly by me. The pairwise stuff could maybe actually have helped,since it might sum all the negative and then all the positive ones one after another (the example actually was sorted, but basically symmetric about zero, which invites anihilation)?
nschloe commentedon Mar 15, 2017
Definitely not, I agree.
It'd be nice to have more options, though, for example
numpy.kahan_sumwith the same signature asnumpy.sum.charris commentedon Mar 15, 2017
The same algorithm used to generate a Hamming code could also be adapted: always summing the two numbers of smallest absolute value. Could be implemented as a priority queue. I'm not recommending that, have just wondered now and then how well it would work...
njsmith commentedon Mar 15, 2017
Sorry, yeah, you would want to sort by absolute value. (I've only used this trick for summing probabilities, where this doesn't come up, so I forgot :-).)
nschloe commentedon Mar 15, 2017
You can do this when summing
floats, but not when summing arrays.njsmith commentedon Mar 15, 2017
@nschloe: you have to sort each array separately, yes. It's awkward but certainly possible, as an option.
wuisawesome commentedon Mar 20, 2017
Would either a kahan_sum/fsum be a feature others think is worth implementing?
asmeurer commentedon Nov 14, 2017
A stable numpy sum would be awesome. Sorting is a PITA since you have to do it by a key (abs), and if you have a more than 1-d array you have to sort each subarray independently.
nschloe commentedon May 12, 2018
For reference, I implemented some stable sums and dot products in accupy. Pretty slow in comparison to
np.sumthough.cdeil commentedon Jun 20, 2019
We would also like to have a more precise sum, for a likelihood that's the sum of ~ a billion numbers.
@nschloe - Very nice comparison in
accupy, thanks!So your conclusion is that the precision of kahan sum isn't much better, so not worth exposing in Numpy?
(kahan is actually already here for a different application, not for numpy.sum)
fsum accuracy seems amazing. How slow is it?
The speed comparison in accupy isn't fair since it's using a Python for loop, no?
(See here).
Is a fsum available (in C or Cython or Numba or ...) somewhere that works on Numpy arrays?
seberg commentedon Jun 20, 2019
@cdeil python uses Shewchuk summation, my guess is you can just look at their code or google a C implementation at the very least. Adapting it into short cython code is probably less work then trying to dig very long.
Now that we support the axis argument for gufuncs, it could actually be a nice little exercise to implement a gufunc for stable summation. Not sure it will be ideal performance wise, but cython solution are unlikely to be any better (unless they bloat up a lot).
nschloe commentedon Jun 20, 2019
Not my conclusion but a known property of Kahan. It's just not robust when it comes to ill-conditioned sums. The best thing would be have fsum (aka Shewchuk) indeed, but there are faster solutions too which work in k-fold machine precision. (See accupy.)
You can acutally try accupy though and see if it fits your needs. If yes, perhaps we can tweak it for speed.
It does indeed. If you can get it done in C++, super!
lorentzenchr commentedon Feb 18, 2024
To add a simple example:
This shows that
numpy.sumdoes better than the naive summation.And for reference (not implying numpy should do the same!), Python's
summeanwhile uses (Kahan-) Neumaier summation, see python/cpython#100425.nschloe commentedon Feb 22, 2024
For those interested, here is an example with a badly conditioned sum:
fsum()computes the sum without error,sum()andnp.sum()are still in the error order of magnitude 10^{-3}. We don't speak ofnaive_sum().asmaier commentedon May 3, 2024
Using Python 3.12.3 on Mac OS 14.1.1 with Apple M3 Pro I get the following results from the script by @nschloe:
The reason why
math.fsum()andsum()now yield the same result might be that since Python 3.12 the algorithm forsum()was improved: "sum() now uses Neumaier summation to improve accuracy and commutativity when summing floats or mixed ints and floats. ", see docs.python.org/3/whatsnew/3.12.htmlNimaSarajpoor commentedon Apr 8, 2025
I am not sure whether I should open a new issue or not. Please let me know.
Issue:
In the following example, I've created two 1D numpy arrays. Both have the same non-zero elements but at different positions. They have different sum !
Example:
seberg commentedon Apr 22, 2025
It's not an issue, it is a basic property of numerical floating point math that re-ordering even the simplest operations can lead to different results. More stable summation may do that less, but I don't think there is any reasonable version that is completely exact.
lorentzenchr commentedon Apr 22, 2025
@seberg What do numpy maintainers intend to do about this issue. I see several options:
sum(what aboutmeanandaverage?)numpy.fsumthat simply promotes python'sfsumto a ufunc.seberg commentedon Apr 22, 2025
Well, I think there is nothing to do about mean/sum directly. We could think about a new function or maybe about a new option to sum/mean (but that is harder).
So I think it's a reasonable request, but a hard one. A new function would be the simplest thing probably.
(I don't see anything to do about documentation.)