annotate include/stats.hpp @ 517:4656f886175e prerelease

reverted to bash, better handling of non existing IDE folder during update_board
author Giulio Moro <giuliomoro@yahoo.it>
date Wed, 22 Jun 2016 15:21:58 +0100
parents 89f28a867a09
children
rev   line source
giuliomoro@156 1 #ifndef STATS_HPP_INCLUDED
giuliomoro@156 2 #define STATS_HPP_INCLUDED
giuliomoro@156 3 #include <stdlib.h>
giuliomoro@156 4 #include <stdio.h>
giuliomoro@156 5 #include <string.h>
giuliomoro@156 6
giuliomoro@156 7 template<class TYPE>
giuliomoro@156 8 class MovingAverage{
giuliomoro@156 9 private:
giuliomoro@156 10 TYPE* array;
giuliomoro@156 11 int length;
giuliomoro@156 12 bool bufferFull;
giuliomoro@156 13 int pointer;
giuliomoro@156 14 TYPE sum;
giuliomoro@156 15 double scale;
giuliomoro@156 16 double average;
giuliomoro@156 17 void dealloc(){
giuliomoro@156 18 free(array);
giuliomoro@156 19 // delete array;
giuliomoro@156 20 }
giuliomoro@156 21
giuliomoro@156 22 void init(int aLength){
giuliomoro@156 23 length=aLength;
giuliomoro@156 24 scale=1.0/length;
giuliomoro@156 25 // array= new TYPE(length); // for some reason this causes memory corruption, so I am using malloc() instead...
giuliomoro@156 26 array=(TYPE*)malloc(sizeof(TYPE)*length);
giuliomoro@156 27 sum=0;
giuliomoro@156 28 if(array==NULL)
giuliomoro@156 29 printf("Error while allocating array\n");
giuliomoro@156 30 memset(array, 0, sizeof(TYPE)*length);
giuliomoro@156 31 reset();
giuliomoro@156 32 }
giuliomoro@156 33 public:
giuliomoro@156 34 MovingAverage(){
giuliomoro@156 35 init(0);
giuliomoro@156 36 }
giuliomoro@156 37 MovingAverage(int aLength){
giuliomoro@156 38 init(aLength);
giuliomoro@156 39 }
giuliomoro@156 40 ~MovingAverage(){
giuliomoro@156 41 dealloc();
giuliomoro@156 42 }
giuliomoro@156 43 int getLength(){
giuliomoro@156 44 return bufferFull ? length : pointer;
giuliomoro@156 45 }
giuliomoro@156 46 void setLength(int aLength){
giuliomoro@156 47 dealloc();
giuliomoro@156 48 init(aLength);
giuliomoro@156 49 }
giuliomoro@156 50 double add(TYPE newElement){
giuliomoro@156 51 sum-=array[pointer];
giuliomoro@156 52 array[pointer]=newElement;
giuliomoro@156 53 sum+=newElement;
giuliomoro@156 54 if(bufferFull==true){
giuliomoro@156 55 average=sum*scale;
giuliomoro@156 56 }
giuliomoro@156 57 else{
giuliomoro@156 58 average=sum/(double)(1+pointer);
giuliomoro@156 59 }
giuliomoro@156 60 pointer++;
giuliomoro@156 61 if(pointer==length){
giuliomoro@156 62 pointer=0;
giuliomoro@156 63 bufferFull=true;
giuliomoro@156 64 }
giuliomoro@156 65 return average;
giuliomoro@156 66 }
giuliomoro@156 67 double getAverage(){
giuliomoro@156 68 return average;
giuliomoro@156 69 }
giuliomoro@156 70 void reset(){
giuliomoro@156 71 pointer=0;
giuliomoro@156 72 bufferFull=false;
giuliomoro@156 73 }
giuliomoro@156 74 };
giuliomoro@156 75
giuliomoro@156 76 #endif /* STATS_HPP_INCLUDED */