/***************************************************************************
                          linearregression.cpp  -  description
                             -------------------
    begin                : Tue Apr 8 2003
    copyright            : (C) 2003 by Martin Merck
    email                : merck@astro.uni-wuerzburg.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "linearregression.h"
#include <math.h>

LinearRegression::LinearRegression()
{
	reset();
}

LinearRegression::~LinearRegression()
{
}

void LinearRegression::reset()
{
	m_dSX  = 0.0;
	m_dSXX = 0.0;
	m_dSY  = 0.0;
	m_dSXY = 0.0;
	m_iNum = 0;
}

void LinearRegression::addPoint( int p_iX, int p_iY )
{
	if( p_iX != -1 && p_iY != -1 )
		addPoint( (double) p_iX, (double) p_iY);
}

void LinearRegression::addPoint( double p_dX, double p_dY )
{
	m_dSX += p_dX;
	m_dSXX += ( p_dX * p_dX );
	m_dSY += p_dY;
	m_dSXY += ( p_dX * p_dY );
	m_iNum++;
}

double LinearRegression::getAxis()
{
	if( m_iNum > 0 )
		return ( (m_dSY / m_iNum) - getSlope() * (m_dSX / m_iNum) );
	else
		return 0.0;
}

double LinearRegression::getSlope()
{
	double dSlope;
	if( m_iNum > 0 )
	{
		dSlope = m_dSXY - ( m_dSX * m_dSY ) / m_iNum;
		dSlope /= m_dSXX - ( m_dSX * m_dSX / m_iNum );
	}
	else
		dSlope = 0.0;
	return dSlope;
}
