OGS
KahanSum.h
Go to the documentation of this file.
1
10#pragma once
11
12#include <spdlog/fmt/bundled/ostream.h>
13
14#include <iomanip>
15#include <ostream>
16#include <range/v3/range/concepts.hpp>
17#include <range/v3/range/traits.hpp>
18
19namespace MathLib
20{
21class KahanSum;
22}
23template <>
24struct fmt::formatter<MathLib::KahanSum> : fmt::ostream_formatter
25{
26};
27
28namespace MathLib
29{
30
32{
33public:
34 explicit constexpr KahanSum(double const value = 0) : value_(value) {}
35
36 explicit constexpr KahanSum(ranges::range auto const& range) : value_(0)
37 {
38 for (auto const v : range)
39 {
40 *this += v;
41 }
42 }
43
44 constexpr KahanSum operator+(double const increment) const
45 {
46 KahanSum result = *this;
47 return result += increment;
48 }
49
50 constexpr KahanSum operator-(double const increment) const
51 {
52 KahanSum result = *this;
53 return result += -increment;
54 }
55
56 constexpr KahanSum& operator-=(double const increment)
57 {
58 return *this += -increment;
59 }
60
61 constexpr KahanSum& operator+=(double const increment)
62 {
63 double const y = increment - correction_;
64 double const t = value_ + y;
65 correction_ = (t - value_) - y;
66 value_ = t;
67 return *this;
68 }
69
70 constexpr double value() const { return value_; }
71 constexpr double operator()() const { return value_; }
72
73 friend inline std::ostream& operator<<(std::ostream& os, KahanSum const& x)
74 {
75 auto const precision = os.precision();
76 return os << std::setprecision(
77 std::numeric_limits<double>::max_digits10)
78 << x.value() << " (± " << x.correction_ << ')'
79 << std::setprecision(precision);
80 }
81
82private:
83 double value_;
84 double correction_ = 0.;
85};
86
87} // namespace MathLib
constexpr KahanSum & operator-=(double const increment)
Definition KahanSum.h:56
constexpr double operator()() const
Definition KahanSum.h:71
constexpr KahanSum(double const value=0)
Definition KahanSum.h:34
friend std::ostream & operator<<(std::ostream &os, KahanSum const &x)
Definition KahanSum.h:73
constexpr KahanSum operator-(double const increment) const
Definition KahanSum.h:50
constexpr KahanSum operator+(double const increment) const
Definition KahanSum.h:44
constexpr double value() const
Definition KahanSum.h:70
double correction_
Definition KahanSum.h:84
constexpr KahanSum & operator+=(double const increment)
Definition KahanSum.h:61
constexpr KahanSum(ranges::range auto const &range)
Definition KahanSum.h:36
static const double v
static const double t