NAMD
Public Member Functions | List of all members
MovingAverage Class Reference

#include <Controller.h>

Public Member Functions

 MovingAverage (int mws=20)
 
void reset (int mws=20)
 
void addSample (double x)
 
double average () const
 

Detailed Description

Maintain moving window average for a collection of samples. Samples contained in a circular queue (newest replacing oldest) implemented using a fixed length vector. Average is updated for each new sample with O(1) work.

Definition at line 46 of file Controller.h.

Constructor & Destructor Documentation

◆ MovingAverage()

MovingAverage::MovingAverage ( int  mws = 20)
inline

Definition at line 53 of file Controller.h.

53  : a(0), n(0), i(0), m(mws) {
54  sample.resize(m);
55  }

Member Function Documentation

◆ addSample()

void MovingAverage::addSample ( double  x)
inline

Definition at line 63 of file Controller.h.

Referenced by Controller::printEnergies().

63  {
64  if (n < m) { // use running average formula
65  sample[i] = x;
66  // XXX I think that the index increment below is faster than
67  // i = (i+1) % m due to avoiding an integer division
68  i = (i < m-1 ? i+1 : 0); // increment i to next available slot
69  double a_old = a;
70  n++;
71  a = a_old + (x - a_old) / n;
72  }
73  else { // use update average formula
74  double x_old = sample[i];
75  sample[i] = x;
76  i = (i < m-1 ? i+1 : 0); // increment i to next available slot
77  a = a + (x - x_old) / n;
78  }
79  }

◆ average()

double MovingAverage::average ( ) const
inline

Definition at line 80 of file Controller.h.

Referenced by Controller::printEnergies().

80 { return a; }

◆ reset()

void MovingAverage::reset ( int  mws = 20)
inline

Definition at line 56 of file Controller.h.

Referenced by Controller::resetMovingAverage().

56  {
57  a=0, n=0, i=0;
58  if (m != mws) {
59  m = mws;
60  sample.resize(m);
61  }
62  }

The documentation for this class was generated from the following file: