WaveBlocksND
kahan_sum.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 
4 namespace waveblocks {
5  namespace math {
17  template<class T>
18  class KahanSum
19  {
20  private:
24  T sum_;
25 
29  T c_;
30 
34  T y_;
35  T t_;
36 
37  public:
46  KahanSum() = default;
47 
55  KahanSum(const T &zero)
56  : sum_(zero)
57  , c_(zero)
58  { }
59 
63  KahanSum(const KahanSum<T> &that) = default;
64 
68  KahanSum &operator=(const KahanSum<T> &that) = default;
69 
75  KahanSum &operator+=(const T &summand)
76  {
77  y_ = summand - c_;
78  t_ = sum_ + y_;
79  c_ = (t_ - sum_) - y_;
80  sum_ = t_;
81  return *this;
82  }
83 
89  const T &operator()() const
90  {
91  return sum_;
92  }
93  };
94  }
95 }
T sum_
Definition: kahan_sum.hpp:24
Definition: coefficients_file_parser.cpp:10
T t_
Definition: kahan_sum.hpp:35
KahanSum()=default
compiler-generated default constructor
T y_
Definition: kahan_sum.hpp:34
T c_
Definition: kahan_sum.hpp:29
KahanSum & operator+=(const T &summand)
adds a number
Definition: kahan_sum.hpp:75
The Kahan&#39;s algorithm achieves O(1) error growth for summing N numbers.
Definition: kahan_sum.hpp:18
KahanSum(const T &zero)
A zero initializing constructor for types that cannot provide a default constructor.
Definition: kahan_sum.hpp:55
KahanSum & operator=(const KahanSum< T > &that)=default
compiler-generated copy assignment operator
const T & operator()() const
retrieves accumulated sum.
Definition: kahan_sum.hpp:89