| Rev | Line | |
|---|
| [33] | 1 | #ifndef _OT_BOILER_H |
|---|
| 2 | #define _OT_BOILER_H |
|---|
| 3 | |
|---|
| 4 | #include "Arduino.h" |
|---|
| 5 | |
|---|
| 6 | #include "BoilerDefinition.h" |
|---|
| 7 | |
|---|
| 8 | /* |
|---|
| 9 | * Simple Moving Average |
|---|
| 10 | */ |
|---|
| 11 | |
|---|
| 12 | template <class V, class M> class SMA { |
|---|
| 13 | |
|---|
| 14 | protected: |
|---|
| 15 | size_t order; |
|---|
| 16 | size_t load; |
|---|
| 17 | size_t last_; |
|---|
| 18 | size_t first_; |
|---|
| 19 | V *value; |
|---|
| 20 | M mean_; |
|---|
| 21 | |
|---|
| 22 | public: |
|---|
| 23 | SMA (size_t order); |
|---|
| 24 | ~SMA (); |
|---|
| 25 | |
|---|
| 26 | bool loaded () const { return (load == order); } |
|---|
| 27 | |
|---|
| 28 | SMA& push (const V& value); |
|---|
| 29 | |
|---|
| 30 | const V& first () const { return value[first_]; } |
|---|
| 31 | const V& last () const { return value[last_]; } |
|---|
| 32 | |
|---|
| 33 | M calc () const; |
|---|
| 34 | M slope () const; |
|---|
| 35 | |
|---|
| 36 | const M& mean () const { return mean_; } |
|---|
| 37 | |
|---|
| 38 | operator M () const { return mean(); } |
|---|
| 39 | }; |
|---|
| 40 | |
|---|
| 41 | template <class V, class M> SMA<V,M>::SMA (size_t o) |
|---|
| 42 | : |
|---|
| 43 | order(o), |
|---|
| 44 | load(0), |
|---|
| 45 | last_(0), |
|---|
| 46 | first_(0), |
|---|
| 47 | mean_(0) |
|---|
| 48 | { |
|---|
| 49 | value = new V[order]; |
|---|
| 50 | value[0] = 0; // pre-init first element in case of access before loaded... |
|---|
| 51 | } |
|---|
| 52 | |
|---|
| 53 | template <class V, class M> SMA<V,M>::~SMA () |
|---|
| 54 | { |
|---|
| 55 | delete value; |
|---|
| 56 | } |
|---|
| 57 | |
|---|
| 58 | template <class V, class M> SMA<V,M>& SMA<V,M>::push (const V& v) |
|---|
| 59 | { |
|---|
| 60 | if (load < order) { |
|---|
| 61 | last_= load++; |
|---|
| 62 | first_ = load; |
|---|
| 63 | value[last_] = v; |
|---|
| 64 | mean_ = calc(); |
|---|
| 65 | } else { |
|---|
| 66 | last_ = first_++; |
|---|
| 67 | V drop(value[last_]); |
|---|
| 68 | value[last_] = v; |
|---|
| 69 | // m(t) = m(t-1) + x(t)/n - x(t-n)/n |
|---|
| 70 | mean_ += M(v-drop)/M(order); |
|---|
| 71 | } |
|---|
| 72 | first_ %= order; |
|---|
| 73 | return *this; |
|---|
| 74 | } |
|---|
| 75 | |
|---|
| 76 | template <class V, class M> M SMA<V,M>::calc () const |
|---|
| 77 | { |
|---|
| 78 | M m(0); |
|---|
| 79 | for (int i=0; i<load; i++) { |
|---|
| 80 | m += M(value[i]); |
|---|
| 81 | } |
|---|
| 82 | return m/M(load); |
|---|
| 83 | } |
|---|
| 84 | |
|---|
| 85 | template <class V, class M> M SMA<V,M>::slope () const |
|---|
| 86 | { |
|---|
| 87 | return (load > 1) ? M(value[last_]-value[first_])/M(load-1) : M(0); |
|---|
| 88 | } |
|---|
| 89 | |
|---|
| 90 | #endif |
|---|
Note: See
TracBrowser
for help on using the repository browser.