Purple Martians
Technical Code Descriptions

Netgame - Rolling Average
Overview Usage Code
Overview Sometime a measured variable has fluctuations that make it unsuitable to use for control purposes. Or other times, you want to display a variable, but it changes so fast it appears blurred as it switches from one value to another. This method provides a rolling average of the last 8 values. Usage
double ping = t2 - t0;          // calculate ping
mwRA[1].add_data(ping);         // send to rolling average
double ping_avg = mwRA[1].avg;  // retrieve average
Code
class mwRollingAverage
{
   public:
   mwRollingAverage(); // default constructor
   void initialize(int arr_siz);
   void add_data(double d);
   double arr[4000];
   int arr_size = 8;
   int    num_filled;
   int    index;
   double last_input;
   double avg;
   double mn;
   double mx;
};
extern mwRollingAverage mRollingAverage[4];


mwRollingAverage::mwRollingAverage()
{
   initialize(8);
}

void mwRollingAverage::initialize(int arr_sz)
{
   for (int i=0; i<400; i++) arr[i] = 0;
   arr_size = arr_sz;
   num_filled = 0;
   index = 0;
   avg = 0;
   last_input = 0;
   mn = 0;
   mx = 0;
}

void mwRollingAverage::add_data(double d)
{
   last_input = d;

   arr[index] = d;  // put new entries where index points
   if (++index > arr_size-1) index = 0;
   num_filled++;

   int ul = arr_size; // find number of valid entries, arr_size by default unless not filled yet
   if (num_filled < arr_size) ul = num_filled;

   mn = std::numeric_limits::max();
   mx = std::numeric_limits::lowest();

   double tally = 0;
   for (int i=0; i < ul; i++) // cycle all the valid entries
   {
      tally += arr[i];
      if (arr[i] < mn) mn = arr[i]; // min
      if (arr[i] > mx) mx = arr[i]; // max
   }
   avg = tally / ul; // average
}
As an added bonus, you can also retrieve: The most recently added value: mwRA[].last_input The minimum value of the values stored: mwRA[].mn The maximum value of the values stored: mwRA[].mx