OGS
KahanSum.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) OpenGeoSys Community (opengeosys.org)
2// SPDX-License-Identifier: BSD-3-Clause
3
4#pragma once
5
6#include <spdlog/fmt/ostr.h>
7
8#include <iomanip>
9#include <ostream>
10#include <range/v3/range/concepts.hpp>
11#include <range/v3/range/traits.hpp>
12
13namespace MathLib
14{
15class KahanSum;
16}
17template <>
18struct fmt::formatter<MathLib::KahanSum> : fmt::ostream_formatter
19{
20};
21
22namespace MathLib
23{
24
26{
27public:
28 explicit constexpr KahanSum(double const value = 0) : value_(value) {}
29
30 explicit constexpr KahanSum(ranges::range auto const& range) : value_(0)
31 {
32 for (auto const v : range)
33 {
34 *this += v;
35 }
36 }
37
38 constexpr KahanSum operator+(double const increment) const
39 {
40 KahanSum result = *this;
41 return result += increment;
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)
51 {
52 return *this += -increment;
53 }
54
55 constexpr KahanSum& operator+=(double const increment)
56 {
57 double const y = increment - correction_;
58 double const t = value_ + y;
59 correction_ = (t - value_) - y;
60 value_ = t;
61 return *this;
62 }
63
64 constexpr double value() const { return value_; }
65 constexpr double operator()() const { return value_; }
66
67 friend inline std::ostream& operator<<(std::ostream& os, KahanSum const& x)
68 {
69 auto const precision = os.precision();
70 return os << std::setprecision(
71 std::numeric_limits<double>::max_digits10)
72 << x.value() << " (± " << x.correction_ << ')'
73 << std::setprecision(precision);
74 }
75
76private:
77 double value_;
78 double correction_ = 0.;
79};
80
81} // namespace MathLib
constexpr KahanSum & operator-=(double const increment)
Definition KahanSum.h:50
constexpr double operator()() const
Definition KahanSum.h:65
constexpr KahanSum(double const value=0)
Definition KahanSum.h:28
friend std::ostream & operator<<(std::ostream &os, KahanSum const &x)
Definition KahanSum.h:67
constexpr KahanSum operator-(double const increment) const
Definition KahanSum.h:44
constexpr KahanSum operator+(double const increment) const
Definition KahanSum.h:38
constexpr double value() const
Definition KahanSum.h:64
double correction_
Definition KahanSum.h:78
constexpr KahanSum & operator+=(double const increment)
Definition KahanSum.h:55
constexpr KahanSum(ranges::range auto const &range)
Definition KahanSum.h:30
static const double v
static const double t