Skip to content

Commit 0a10e16

Browse files
Add class to compute running average
STATUS: Builds - Justin C Signed-off-by: PhyXTGears <phyxtgearspro@gmail.com>
1 parent b4b0e09 commit 0a10e16

File tree

4 files changed

+64
-1
lines changed

4 files changed

+64
-1
lines changed

.vscode/settings.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@
1515
"files.associations": {
1616
"*.inc": "cpp",
1717
"cmath": "cpp"
18-
}
18+
},
19+
"C_Cpp.default.configurationProvider": "vscode-wpilib"
1920
}

gradlew

100644100755
File mode changed.

src/main/cpp/util/RunningAverage.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
#include "util/RunningAverage.h"
3+
4+
template <class T>
5+
RunningAverage<T>::RunningAverage(size_t capacity)
6+
: m_Capacity(capacity)
7+
, m_Count(0)
8+
, m_Index(0)
9+
, m_Total(0.0)
10+
, m_Average(0.0)
11+
{
12+
m_Values = new T[capacity];
13+
}
14+
15+
template <class T>
16+
RunningAverage<T>::~RunningAverage() {
17+
delete m_Values;
18+
}
19+
20+
template <class T>
21+
void RunningAverage<T>::PushValue(T val) {
22+
m_Total -= m_Values[m_Index];
23+
m_Total += val;
24+
25+
m_Values[m_Index] = val;
26+
m_Count = std::min(m_Count, m_Capacity);
27+
m_Index = (m_Index + 1) % m_Capacity;
28+
29+
if (0 < m_Count) {
30+
m_Average = m_Total / m_Count;
31+
}
32+
}
33+
34+
template <class T>
35+
T RunningAverage<T>::GetAverage() {
36+
return m_Average;
37+
}
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <cstdlib>
2+
#include <algorithm>
3+
4+
template <class T>
5+
class RunningAverage {
6+
public:
7+
// Create an instance that stores the given number of elements.
8+
RunningAverage(size_t);
9+
~RunningAverage();
10+
11+
// Push a value onto the ring buffer, and drop any extra values.
12+
void PushValue(T);
13+
14+
// Return the value of the running average.
15+
T GetAverage();
16+
17+
private:
18+
T *m_Values;
19+
size_t m_Capacity;
20+
size_t m_Count;
21+
size_t m_Index;
22+
23+
T m_Total;
24+
T m_Average;
25+
};

0 commit comments

Comments
 (0)