Created
March 16, 2023 14:04
-
-
Save willeccles/d7fba056a851a4be16a2cd1910c59ef6 to your computer and use it in GitHub Desktop.
C++ Kahan summation utility class
This file contains hidden or 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
// 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