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