comparison include/stats.hpp @ 137:aac018615930 ClockSync

MovingAverage now returns a meaningful value also when the buffer is not full
author Giulio Moro <giuliomoro@yahoo.it>
date Sun, 13 Sep 2015 21:31:37 +0100
parents e77e2e712fbc
children 5edc6d0713ef
comparison
equal deleted inserted replaced
136:772dbb57442b 137:aac018615930
7 template<class TYPE> 7 template<class TYPE>
8 class MovingAverage{ 8 class MovingAverage{
9 private: 9 private:
10 TYPE* array; 10 TYPE* array;
11 int length; 11 int length;
12 bool bufferFull;
12 int pointer; 13 int pointer;
13 TYPE sum; 14 TYPE sum;
14 double scale; 15 double scale;
15 double average; 16 double average;
16 void dealloc(){ 17 void dealloc(){
17 free(array); 18 free(array);
18 // delete array; 19 // delete array;
19 } 20 }
20 21
21 void init(int aLength){ 22 void init(int aLength){
22 length=aLength; 23 length=aLength;
26 sum=0; 27 sum=0;
27 if(array==NULL) 28 if(array==NULL)
28 printf("Error while allocating array\n"); 29 printf("Error while allocating array\n");
29 memset(array, 0, sizeof(TYPE)*length); 30 memset(array, 0, sizeof(TYPE)*length);
30 pointer=0; 31 pointer=0;
32 bufferFull=false;
31 } 33 }
32 public: 34 public:
33 MovingAverage(){ 35 MovingAverage(){
34 init(0); 36 init(0);
35 } 37 }
48 } 50 }
49 double add(TYPE newElement){ 51 double add(TYPE newElement){
50 sum-=array[pointer]; 52 sum-=array[pointer];
51 array[pointer]=newElement; 53 array[pointer]=newElement;
52 sum+=newElement; 54 sum+=newElement;
53 average=sum*scale; 55 if(bufferFull==true){
56 average=sum*scale;
57 }
58 else{
59 average=sum/(double)(1+pointer);
60 }
54 pointer++; 61 pointer++;
55 if(pointer==length) 62 if(pointer==length){
56 pointer=0; 63 pointer=0;
64 bufferFull=true;
65 }
57 return average; 66 return average;
58 } 67 }
59 double getAverage(){ 68 double getAverage(){
60 return average; 69 return average;
61 } 70 }