Mercurial > hg > beaglert
comparison include/stats.hpp @ 135:e77e2e712fbc ClockSync
To work with the ClockSync plugin
author | Giulio Moro <giuliomoro@yahoo.it> |
---|---|
date | Sat, 12 Sep 2015 20:05:55 +0100 |
parents | |
children | aac018615930 |
comparison
equal
deleted
inserted
replaced
133:04b1678614c9 | 135:e77e2e712fbc |
---|---|
1 #ifndef STATS_HPP_INCLUDED | |
2 #define STATS_HPP_INCLUDED | |
3 #include <stdlib.h> | |
4 #include <stdio.h> | |
5 #include <string.h> | |
6 | |
7 template<class TYPE> | |
8 class MovingAverage{ | |
9 private: | |
10 TYPE* array; | |
11 int length; | |
12 int pointer; | |
13 TYPE sum; | |
14 double scale; | |
15 double average; | |
16 void dealloc(){ | |
17 free(array); | |
18 // delete array; | |
19 } | |
20 | |
21 void init(int aLength){ | |
22 length=aLength; | |
23 scale=1.0/length; | |
24 // array= new TYPE(length); // for some reason this causes memory corruption, so I am using malloc() instead... | |
25 array=(TYPE*)malloc(sizeof(TYPE)*length); | |
26 sum=0; | |
27 if(array==NULL) | |
28 printf("Error while allocating array\n"); | |
29 memset(array, 0, sizeof(TYPE)*length); | |
30 pointer=0; | |
31 } | |
32 public: | |
33 MovingAverage(){ | |
34 init(0); | |
35 } | |
36 MovingAverage(int aLength){ | |
37 init(aLength); | |
38 } | |
39 ~MovingAverage(){ | |
40 dealloc(); | |
41 } | |
42 int getLength(){ | |
43 return length; | |
44 } | |
45 void setLength(int aLength){ | |
46 dealloc(); | |
47 init(aLength); | |
48 } | |
49 double add(TYPE newElement){ | |
50 sum-=array[pointer]; | |
51 array[pointer]=newElement; | |
52 sum+=newElement; | |
53 average=sum*scale; | |
54 pointer++; | |
55 if(pointer==length) | |
56 pointer=0; | |
57 return average; | |
58 } | |
59 double getAverage(){ | |
60 return average; | |
61 } | |
62 }; | |
63 | |
64 #endif /* STATS_HPP_INCLUDED */ |