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