annotate include/stats.hpp @ 140:5edc6d0713ef ClockSync

MovingAverage: added reset() method and edited getLength() to return current length
author Giulio Moro <giuliomoro@yahoo.it>
date Mon, 14 Sep 2015 14:57:54 +0100
parents aac018615930
children
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@137 12 bool bufferFull;
giuliomoro@135 13 int pointer;
giuliomoro@135 14 TYPE sum;
giuliomoro@135 15 double scale;
giuliomoro@135 16 double average;
giuliomoro@135 17 void dealloc(){
giuliomoro@137 18 free(array);
giuliomoro@135 19 // delete array;
giuliomoro@135 20 }
giuliomoro@135 21
giuliomoro@135 22 void init(int aLength){
giuliomoro@135 23 length=aLength;
giuliomoro@135 24 scale=1.0/length;
giuliomoro@135 25 // array= new TYPE(length); // for some reason this causes memory corruption, so I am using malloc() instead...
giuliomoro@135 26 array=(TYPE*)malloc(sizeof(TYPE)*length);
giuliomoro@135 27 sum=0;
giuliomoro@135 28 if(array==NULL)
giuliomoro@135 29 printf("Error while allocating array\n");
giuliomoro@135 30 memset(array, 0, sizeof(TYPE)*length);
giuliomoro@140 31 reset();
giuliomoro@135 32 }
giuliomoro@135 33 public:
giuliomoro@135 34 MovingAverage(){
giuliomoro@135 35 init(0);
giuliomoro@135 36 }
giuliomoro@135 37 MovingAverage(int aLength){
giuliomoro@135 38 init(aLength);
giuliomoro@135 39 }
giuliomoro@135 40 ~MovingAverage(){
giuliomoro@135 41 dealloc();
giuliomoro@135 42 }
giuliomoro@135 43 int getLength(){
giuliomoro@140 44 return bufferFull ? length : pointer;
giuliomoro@135 45 }
giuliomoro@135 46 void setLength(int aLength){
giuliomoro@135 47 dealloc();
giuliomoro@135 48 init(aLength);
giuliomoro@135 49 }
giuliomoro@135 50 double add(TYPE newElement){
giuliomoro@135 51 sum-=array[pointer];
giuliomoro@135 52 array[pointer]=newElement;
giuliomoro@135 53 sum+=newElement;
giuliomoro@137 54 if(bufferFull==true){
giuliomoro@137 55 average=sum*scale;
giuliomoro@137 56 }
giuliomoro@137 57 else{
giuliomoro@137 58 average=sum/(double)(1+pointer);
giuliomoro@137 59 }
giuliomoro@135 60 pointer++;
giuliomoro@137 61 if(pointer==length){
giuliomoro@135 62 pointer=0;
giuliomoro@137 63 bufferFull=true;
giuliomoro@137 64 }
giuliomoro@135 65 return average;
giuliomoro@135 66 }
giuliomoro@135 67 double getAverage(){
giuliomoro@135 68 return average;
giuliomoro@135 69 }
giuliomoro@140 70 void reset(){
giuliomoro@140 71 pointer=0;
giuliomoro@140 72 bufferFull=false;
giuliomoro@140 73 }
giuliomoro@135 74 };
giuliomoro@135 75
giuliomoro@137 76 #endif /* STATS_HPP_INCLUDED */