/** 
 * @file RunningStat.cpp
 * @brief B. P. Welford Computation of Mean and Variance download at: http://www.johndcook.com/standard_deviation.html
 * @author Michael Koch
 * @date 18/02/2009
 */

#include "core/image/ImageT.h"
#include "core/vector/VectorT.h"
#include "core/vector/MatrixT.h"

#include "vislearning/baselib/RunningStat.h"

using namespace OBJREC;
using namespace std;
using namespace NICE;

void RunningStat::Clear()
{
     m_n = 0;
}

void RunningStat::Push(double x)
{
     m_n++;

            // See Knuth TAOCP vol 2, 3rd edition, page 232
     if (m_n == 1)
     {
          m_oldM = m_newM = x;
          m_oldS = 0.0;
     }
     else
     {
          m_newM = m_oldM + (x - m_oldM)/m_n;
          m_newS = m_oldS + (x - m_oldM)*(x - m_newM);
    
                // set up for next iteration
          m_oldM = m_newM; 
          m_oldS = m_newS;
     }
}

size_t RunningStat::NumDataValues() const
{
     return m_n;
}

double RunningStat::Mean() const
{
     return (m_n > 0) ? m_newM : 0.0;
}

double RunningStat::Variance() const
{
     return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 );
}

double RunningStat::StandardDeviation() const
{
     return sqrt( Variance() );
}



