Use Kahan summation for fsum and fsumf #742
Open
+24
−12
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This compensated summation gives a more precise result than the original algorithm, as demonstrated through extra precision in the tests. It also drops recursion and the extra branching.
I used double precision internally for fsumf since I assume its purpose is to interface with single precision, not necessary constrain itself to only using single precision. If needed, it can be trivially changed to use single precision internally while still passing the tests.
In fsumf, naive summation using double precision is likely sufficient, and more precise than single precision Kaham summation. In other words, Kahan summation with double precision in fsumf may be overkill.
In the fsumf test, neither 10000.1 nor 1.1 can be represented exactly. The former is rounded down and the latter is rounded up (by less) to the nearest representable value. As a result, the most precise sum is just shy of the "obvious" result.
Changing the tests isn't strictly necessary. I wanted tests that fail under the old implementation but pass with the new.