RunningStat.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @file RunningStat.cpp
  3. * @brief B. P. Welford Computation of Mean and Variance download at: http://www.johndcook.com/standard_deviation.html
  4. * @author Michael Koch
  5. * @date 18/02/2009
  6. */
  7. #ifdef NOVISUAL
  8. #include <vislearning/nice_nonvis.h>
  9. #else
  10. #include <vislearning/nice.h>
  11. #endif
  12. #include "vislearning/baselib/RunningStat.h"
  13. using namespace OBJREC;
  14. using namespace std;
  15. using namespace NICE;
  16. void RunningStat::Clear()
  17. {
  18. m_n = 0;
  19. }
  20. void RunningStat::Push(double x)
  21. {
  22. m_n++;
  23. // See Knuth TAOCP vol 2, 3rd edition, page 232
  24. if (m_n == 1)
  25. {
  26. m_oldM = m_newM = x;
  27. m_oldS = 0.0;
  28. }
  29. else
  30. {
  31. m_newM = m_oldM + (x - m_oldM)/m_n;
  32. m_newS = m_oldS + (x - m_oldM)*(x - m_newM);
  33. // set up for next iteration
  34. m_oldM = m_newM;
  35. m_oldS = m_newS;
  36. }
  37. }
  38. size_t RunningStat::NumDataValues() const
  39. {
  40. return m_n;
  41. }
  42. double RunningStat::Mean() const
  43. {
  44. return (m_n > 0) ? m_newM : 0.0;
  45. }
  46. double RunningStat::Variance() const
  47. {
  48. return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 );
  49. }
  50. double RunningStat::StandardDeviation() const
  51. {
  52. return sqrt( Variance() );
  53. }