HART  0.2.0
High level Audio Regression and Testing
Loading...
Searching...
No Matches
hart_accurate_sum.hpp
Go to the documentation of this file.
1#pragma once
2
3namespace hart
4{
5
6///@brief Implements Kahan algorithm for floating point accumulations
7///@tparam SampleType Type of values to accumulate, typically `float` or `double`
8///@ingroup Utilities
9template<typename SampleType>
11{
12public:
13 ///@brief Inits AccurateSum with a specific value
14 ///@param initialSum Initial sum value
15 AccurateSum (SampleType initialSum = (SampleType) 0):
16 m_sum (initialSum),
17 m_compensation ((SampleType) 0)
18 {
19 }
20
21 ///@brief Assigns AccurateSum's accumulated sum to a specific value
22 ///@param initialSum Initial sum value
23 AccurateSum& operator= (SampleType initialSum)
24 {
25 m_sum = initialSum;
26 m_compensation = (SampleType) 0;
27 return *this;
28 }
29
30 /// @brief Adds a value to a sum, tracking the potential floating point error
31 /// @param value Value to add to the sum
32 /// @return Reference to updated AccurateSum
33 AccurateSum& operator+= (SampleType value)
34 {
35 const SampleType corrected = value - m_compensation;
36 const SampleType newSum = m_sum + corrected;
37 m_compensation = (newSum - m_sum) - corrected;
38 m_sum = newSum;
39 return *this;
40 }
41
42 /// @brief Value accumulated by the += operator
43 operator SampleType() const
44 {
45 return m_sum;
46 }
47
48 /// @brief Value accumulated by the += operator, converted to the requested type
49 template<typename RequestedType>
50 RequestedType get() const
51 {
52 return static_cast<RequestedType> (m_sum);
53 }
54
55 SampleType getValue() const
56 {
57 return m_sum;
58 }
59
60private:
61 SampleType m_sum;
62 SampleType m_compensation;
63};
64
65} // namespace hart
Implements Kahan algorithm for floating point accumulations.
RequestedType get() const
Value accumulated by the += operator, converted to the requested type.
AccurateSum(SampleType initialSum=(SampleType) 0)
Inits AccurateSum with a specific value.
SampleType getValue() const
AccurateSum & operator+=(SampleType value)
Adds a value to a sum, tracking the potential floating point error.
operator SampleType() const
Value accumulated by the += operator.
AccurateSum & operator=(SampleType initialSum)
Assigns AccurateSum's accumulated sum to a specific value.