Skip to content

Instantly share code, notes, and snippets.

@willeccles
Created March 16, 2023 14:04
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 willeccles/d7fba056a851a4be16a2cd1910c59ef6 to your computer and use it in GitHub Desktop.
Save willeccles/d7fba056a851a4be16a2cd1910c59ef6 to your computer and use it in GitHub Desktop.
C++ Kahan summation utility class
// TODO concepts/constraints/SFINAE to keep T as FP
// TODO make this more robust than the very basics
template <class T>
class KahanSum {
public:
KahanSum() : sum_{}, err_{} {}
KahanSum(T init) : sum_{init}, err_{} {}
constexpr KahanSum& Add(T val) {
T y = val - err_;
T t = sum_ + y;
err_ = (t - sum_) - y;
sum_ = t;
return *this;
}
constexpr KahanSum& Sub(T val) {
return Add(-val);
}
constexpr T Get() const {
return sum_;
}
constexpr KahanSum& operator=(T val) {
sum_ = val;
err_ = 0;
return *this;
}
constexpr KahanSum& operator+=(T val) {
return Add(val);
}
constexpr KahanSum& operator-=(T val) {
return Sub(val);
}
constexpr operator T() const {
return Get();
}
private:
T sum_;
T err_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment