Created
August 24, 2016 11:23
-
-
Save daniel-j-h/cd649b939079bc2869c1787471085d6b to your computer and use it in GitHub Desktop.
Kahan Summation: more accurate summation of floating point numbers (https://en.wikipedia.org/wiki/Kahan_summation_algorithm)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iterator> | |
template <typename Iter> | |
typename std::iterator_traits<Iter>::value_type KahanSum(Iter first, Iter last) { | |
using T = typename std::iterator_traits<Iter>::value_type; | |
T sum(0); | |
T compensation(0); | |
for (; first != last; ++first) { | |
compensation += *first; | |
const T next(sum + compensation); | |
compensation += sum - next; | |
sum = next; | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also available in Boost