# HG changeset patch # User Giulio Moro # Date 1444257532 -3600 # Node ID 89f28a867a090c6d8b30b45b5c442a8aa26464df # Parent 13d25cbcde03d6181716c2bca72d4919b5d46a35 Imported stats.hpp from other branch. This includes moving average template class diff -r 13d25cbcde03 -r 89f28a867a09 include/stats.hpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/include/stats.hpp Wed Oct 07 23:38:52 2015 +0100 @@ -0,0 +1,76 @@ +#ifndef STATS_HPP_INCLUDED +#define STATS_HPP_INCLUDED +#include +#include +#include + +template +class MovingAverage{ +private: + TYPE* array; + int length; + bool bufferFull; + int pointer; + TYPE sum; + double scale; + double average; + void dealloc(){ + free(array); + // delete array; + } + + void init(int aLength){ + length=aLength; + scale=1.0/length; + // array= new TYPE(length); // for some reason this causes memory corruption, so I am using malloc() instead... + array=(TYPE*)malloc(sizeof(TYPE)*length); + sum=0; + if(array==NULL) + printf("Error while allocating array\n"); + memset(array, 0, sizeof(TYPE)*length); + reset(); + } +public: + MovingAverage(){ + init(0); + } + MovingAverage(int aLength){ + init(aLength); + } + ~MovingAverage(){ + dealloc(); + } + int getLength(){ + return bufferFull ? length : pointer; + } + void setLength(int aLength){ + dealloc(); + init(aLength); + } + double add(TYPE newElement){ + sum-=array[pointer]; + array[pointer]=newElement; + sum+=newElement; + if(bufferFull==true){ + average=sum*scale; + } + else{ + average=sum/(double)(1+pointer); + } + pointer++; + if(pointer==length){ + pointer=0; + bufferFull=true; + } + return average; + } + double getAverage(){ + return average; + } + void reset(){ + pointer=0; + bufferFull=false; + } +}; + +#endif /* STATS_HPP_INCLUDED */