RunningStat.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #include "core/image/ImageT.h"
  8. #include "core/vector/VectorT.h"
  9. #include "core/vector/MatrixT.h"
  10. #include "vislearning/baselib/RunningStat.h"
  11. using namespace OBJREC;
  12. using namespace std;
  13. using namespace NICE;
  14. void RunningStat::Clear()
  15. {
  16. m_n = 0;
  17. }
  18. void RunningStat::Push(double x)
  19. {
  20. m_n++;
  21. // See Knuth TAOCP vol 2, 3rd edition, page 232
  22. if (m_n == 1)
  23. {
  24. m_oldM = m_newM = x;
  25. m_oldS = 0.0;
  26. }
  27. else
  28. {
  29. m_newM = m_oldM + (x - m_oldM)/m_n;
  30. m_newS = m_oldS + (x - m_oldM)*(x - m_newM);
  31. // set up for next iteration
  32. m_oldM = m_newM;
  33. m_oldS = m_newS;
  34. }
  35. }
  36. size_t RunningStat::NumDataValues() const
  37. {
  38. return m_n;
  39. }
  40. double RunningStat::Mean() const
  41. {
  42. return (m_n > 0) ? m_newM : 0.0;
  43. }
  44. double RunningStat::Variance() const
  45. {
  46. return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 );
  47. }
  48. double RunningStat::StandardDeviation() const
  49. {
  50. return sqrt( Variance() );
  51. }