nidas  v1.2-1520
RunningAverage.h
Go to the documentation of this file.
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4; -*-
2 // vim: set shiftwidth=4 softtabstop=4 expandtab:
3 /*
4  ********************************************************************
5  ** NIDAS: NCAR In-situ Data Acquistion Software
6  **
7  ** 2007, Copyright University Corporation for Atmospheric Research
8  **
9  ** This program is free software; you can redistribute it and/or modify
10  ** it under the terms of the GNU General Public License as published by
11  ** the Free Software Foundation; either version 2 of the License, or
12  ** (at your option) any later version.
13  **
14  ** This program is distributed in the hope that it will be useful,
15  ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16  ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  ** GNU General Public License for more details.
18  **
19  ** The LICENSE.txt file accompanying this software contains
20  ** a copy of the GNU General Public License. If it is not found,
21  ** write to the Free Software Foundation, Inc.,
22  ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  **
24  ********************************************************************
25 */
26 /*
27  ********************************************************************
28  Copyright by the National Center for Atmospheric Research
29 
30  $Revision$
31 
32  $LastChangedDate$
33 
34  $LastChangedRevision$
35 
36  $LastChangedBy$
37 
38  $HeadURL$
39  ********************************************************************
40 */
41 
42 #ifndef _nidis_util_RunningAverage_h_
43 #define _nidis_util_RunningAverage_h_
44 
45 #include <cstring>
46 
47 namespace nidas { namespace util {
48 
53 template<class T, int i> class RunningAverage
54 {
55 public:
57  { memset((char *)_values, 0, sizeof(_values)); }
58 
59  T average(T newValue)
60  {
61  _sum -= _values[_index];
62  _values[_index++] = newValue;
63  _sum += newValue;
64 
65  if (_nValues < _size)
66  ++_nValues;
67 
68  if (_index >= _size)
69  _index = 0;
70 
71  return (T)(_sum / _nValues);
72  }
73 
74 private:
75  T _values[i];
76  unsigned int _size;
77 
78  double _sum;
79 
80  unsigned int _nValues;
81  unsigned int _index;
82 };
83 
84 } }
85 
86 #endif
unsigned int _size
Definition: RunningAverage.h:76
double _sum
Definition: RunningAverage.h:78
unsigned int _index
Definition: RunningAverage.h:81
T _values[i]
Definition: RunningAverage.h:75
unsigned int _nValues
Definition: RunningAverage.h:80
RunningAverage()
Definition: RunningAverage.h:56
Basic running average template class.
Definition: RunningAverage.h:53
T average(T newValue)
Definition: RunningAverage.h:59