giuliomoro@156: #ifndef STATS_HPP_INCLUDED giuliomoro@156: #define STATS_HPP_INCLUDED giuliomoro@156: #include giuliomoro@156: #include giuliomoro@156: #include giuliomoro@156: giuliomoro@156: template giuliomoro@156: class MovingAverage{ giuliomoro@156: private: giuliomoro@156: TYPE* array; giuliomoro@156: int length; giuliomoro@156: bool bufferFull; giuliomoro@156: int pointer; giuliomoro@156: TYPE sum; giuliomoro@156: double scale; giuliomoro@156: double average; giuliomoro@156: void dealloc(){ giuliomoro@156: free(array); giuliomoro@156: // delete array; giuliomoro@156: } giuliomoro@156: giuliomoro@156: void init(int aLength){ giuliomoro@156: length=aLength; giuliomoro@156: scale=1.0/length; giuliomoro@156: // array= new TYPE(length); // for some reason this causes memory corruption, so I am using malloc() instead... giuliomoro@156: array=(TYPE*)malloc(sizeof(TYPE)*length); giuliomoro@156: sum=0; giuliomoro@156: if(array==NULL) giuliomoro@156: printf("Error while allocating array\n"); giuliomoro@156: memset(array, 0, sizeof(TYPE)*length); giuliomoro@156: reset(); giuliomoro@156: } giuliomoro@156: public: giuliomoro@156: MovingAverage(){ giuliomoro@156: init(0); giuliomoro@156: } giuliomoro@156: MovingAverage(int aLength){ giuliomoro@156: init(aLength); giuliomoro@156: } giuliomoro@156: ~MovingAverage(){ giuliomoro@156: dealloc(); giuliomoro@156: } giuliomoro@156: int getLength(){ giuliomoro@156: return bufferFull ? length : pointer; giuliomoro@156: } giuliomoro@156: void setLength(int aLength){ giuliomoro@156: dealloc(); giuliomoro@156: init(aLength); giuliomoro@156: } giuliomoro@156: double add(TYPE newElement){ giuliomoro@156: sum-=array[pointer]; giuliomoro@156: array[pointer]=newElement; giuliomoro@156: sum+=newElement; giuliomoro@156: if(bufferFull==true){ giuliomoro@156: average=sum*scale; giuliomoro@156: } giuliomoro@156: else{ giuliomoro@156: average=sum/(double)(1+pointer); giuliomoro@156: } giuliomoro@156: pointer++; giuliomoro@156: if(pointer==length){ giuliomoro@156: pointer=0; giuliomoro@156: bufferFull=true; giuliomoro@156: } giuliomoro@156: return average; giuliomoro@156: } giuliomoro@156: double getAverage(){ giuliomoro@156: return average; giuliomoro@156: } giuliomoro@156: void reset(){ giuliomoro@156: pointer=0; giuliomoro@156: bufferFull=false; giuliomoro@156: } giuliomoro@156: }; giuliomoro@156: giuliomoro@156: #endif /* STATS_HPP_INCLUDED */