-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswa.h
More file actions
60 lines (48 loc) · 1.22 KB
/
swa.h
File metadata and controls
60 lines (48 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifndef _SWA_H
#define _SWA_H
class SimpleRingBuffer {
public:
SimpleRingBuffer() { flush(); }
constexpr size_t count() const { return Count; }
SimpleRingBuffer &push(Type value) {
m_buffer[m_head] = value;
m_head++;
if (m_head == Count) {
m_head = 0;
}
return *this;
}
Type back() const { return m_buffer[m_head]; }
Type front() const { return at(0); }
Type at(size_t offset) {
const auto adjusted_offset
= m_head > offset ? m_head - offset - 1 : Count + m_head - offset - 1;
return m_buffer[adjusted_offset];
}
SimpleRingBuffer &flush() {
for (auto &value : m_buffer) {
value = {};
}
m_head = 0;
return *this;
}
private:
size_t m_head = 0;
var::Array<Type, Count> m_buffer;
};
template <typename Type, size_t Count>
class SimpleMovingAverage {
public:
constexpr size_t count() const { return Count; }
SimpleMovingAverage &calculate(Type input) {
sum += input;
sum -= m_buffer.back();
m_buffer.push(input);
return *this;
}
Type present_value() const { return sum / Count; }
private:
SimpleRingBuffer<Type, Count> m_buffer;
Type sum = {};
};
#endif