annotate 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
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@135 31 pointer=0;
giuliomoro@137 32 bufferFull=false;
giuliomoro@135 33 }
giuliomoro@135 34 public:
giuliomoro@135 35 MovingAverage(){
giuliomoro@135 36 init(0);
giuliomoro@135 37 }
giuliomoro@135 38 MovingAverage(int aLength){
giuliomoro@135 39 init(aLength);
giuliomoro@135 40 }
giuliomoro@135 41 ~MovingAverage(){
giuliomoro@135 42 dealloc();
giuliomoro@135 43 }
giuliomoro@135 44 int getLength(){
giuliomoro@135 45 return length;
giuliomoro@135 46 }
giuliomoro@135 47 void setLength(int aLength){
giuliomoro@135 48 dealloc();
giuliomoro@135 49 init(aLength);
giuliomoro@135 50 }
giuliomoro@135 51 double add(TYPE newElement){
giuliomoro@135 52 sum-=array[pointer];
giuliomoro@135 53 array[pointer]=newElement;
giuliomoro@135 54 sum+=newElement;
giuliomoro@137 55 if(bufferFull==true){
giuliomoro@137 56 average=sum*scale;
giuliomoro@137 57 }
giuliomoro@137 58 else{
giuliomoro@137 59 average=sum/(double)(1+pointer);
giuliomoro@137 60 }
giuliomoro@135 61 pointer++;
giuliomoro@137 62 if(pointer==length){
giuliomoro@135 63 pointer=0;
giuliomoro@137 64 bufferFull=true;
giuliomoro@137 65 }
giuliomoro@135 66 return average;
giuliomoro@135 67 }
giuliomoro@135 68 double getAverage(){
giuliomoro@135 69 return average;
giuliomoro@135 70 }
giuliomoro@135 71 };
giuliomoro@135 72
giuliomoro@137 73 #endif /* STATS_HPP_INCLUDED */