comparison include/stats.hpp @ 156:89f28a867a09

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