numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
kahan_adder.h
Go to the documentation of this file.
1/*
2 * Copyright 2021 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
23
24namespace num_collect::util {
25
31template <concepts::kahan_addable T>
33public:
40 kahan_adder() : kahan_adder(static_cast<T>(0)) {}
41
49 explicit kahan_adder(const T& zero)
50 : sum_(zero), rem_(zero), prev_sum_(zero) {}
51
58 auto add(const T& value) -> kahan_adder& {
60 rem_ += value;
61 sum_ += rem_;
62 rem_ -= sum_ - prev_sum_;
63 return *this;
64 }
65
72 auto sub(const T& value) -> kahan_adder& {
74 rem_ += -value;
75 sum_ += rem_;
76 rem_ -= sum_ - prev_sum_;
77 return *this;
78 }
79
86 auto operator+=(const T& value) -> kahan_adder& {
87 add(value);
88 return *this;
89 }
90
97 auto operator-=(const T& value) -> kahan_adder& {
98 sub(value);
99 return *this;
100 }
101
107 [[nodiscard]] auto sum() const noexcept -> const T& { return sum_; }
108
114 operator T() const { // NOLINT: Allow implicit conversion.
115 return sum_;
116 }
117
118private:
121
124
127};
128
129} // namespace num_collect::util
Class to add numbers using Kahan summation kahan1965.
Definition kahan_adder.h:32
kahan_adder(const T &zero)
Construct with zero number.
Definition kahan_adder.h:49
auto operator+=(const T &value) -> kahan_adder &
Add a number.
Definition kahan_adder.h:86
auto add(const T &value) -> kahan_adder &
Add a number.
Definition kahan_adder.h:58
auto operator-=(const T &value) -> kahan_adder &
Subtract a number.
Definition kahan_adder.h:97
auto sum() const noexcept -> const T &
Get sum.
auto sub(const T &value) -> kahan_adder &
Subtract a number.
Definition kahan_adder.h:72
Definition of kahan_addable concept.
Namespace of utilities.
Definition assert.h:30