Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Created August 24, 2016 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-j-h/cd649b939079bc2869c1787471085d6b to your computer and use it in GitHub Desktop.
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)
#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;
}
@daniel-j-h
Copy link
Author

Also available in Boost

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment