TinyRobotics
Loading...
Searching...
No Matches
MovingAverage.h
1#pragma once
2#include <list>
3
4namespace tinyrobotics {
5
6
7/**
8 * @class MovingAverage
9 * @ingroup control
10 * @brief Computes the moving average of a sequence of values.
11 *
12 * This template class maintains a fixed-size window of the most recent values and efficiently computes
13 * their arithmetic mean. It is useful for smoothing noisy sensor data, filtering out short-term fluctuations,
14 * and providing a simple low-pass filter in embedded and robotics applications.
15 *
16 * ## Features
17 * - Generic: supports any numeric type (float, int, double, etc.)
18 * - Fixed window size, configurable at runtime
19 * - Efficient update and calculation
20 *
21 * ## Usage Example
22 * @code
23 * MovingAverage<float> avg(5); // 5-sample moving average
24 * avg.addMeasurement(1.0f);
25 * avg.addMeasurement(2.0f);
26 * float mean = avg.calculate();
27 * @endcode
28 *
29 * @tparam N Numeric type of the values (e.g., float, int)
30 *
31 * @author Phil Schatzmann
32
33 */
34
35template <class N = float>
36class MovingAverage {
37 public:
38 MovingAverage(size_t size) {
39 setSize(size);
40 }
41
42 void addMeasurement(N value) {
43 if (this->values.size() == this->size) {
44 this->values.pop_front();
45 }
46 this->values.push_back(value);
47 }
48
49 float calculate() {
50 float sum = 0;
51 for (int i = 0; i < this->values.size(); i++) {
52 sum += this->values[i];
53 }
54 return sum / this->values.size();
55 }
56
57 /// Defines the number of values
58 void setSize(size_t size) {
59 this->size = size;
60 }
61
62 protected:
63 std::list<N> values;
64 size_t size = 0;;
65};
66
67} // namespace tinyrobotics
Computes the moving average of a sequence of values.
Definition: MovingAverage.h:36
void setSize(size_t size)
Defines the number of values.
Definition: MovingAverage.h:58