#ifndef QRK_LEAST_SQUARE_H
#define QRK_LEAST_SQUARE_H

/*!
  \file
  \brief 一次の最小二乗法

  http://ja.wikipedia.org/wiki/最小二乗法 より

  \author Satofumi KAMIMURA

  $Id: leastSquare.h 1448 2009-10-25 14:05:02Z satofumi $
*/

#include "Point.h"
#include <vector>


namespace qrk
{
  /*!
    \brief 最小自乗法による直線推定

    \param[out] a 傾き
    \param[out] b 切片
    \param[in] points 点
    \param[in] n 点の個数
  */
  template <typename T>
  void leastSquare(double& a, double& b, const Point<T> points[], size_t n)
  {
    long x_total = 0;
    long y_total = 0;
    long xy_total = 0;
    long xx_total = 0;

    for (size_t i = 0; i < n; ++i) {
      const Point<T>& p = points[i];
      x_total += p.x;
      y_total += p.y;
      xy_total += p.x * p.y;
      xx_total += p.x * p.x;
    }

    double num = n;
    double denominator = (num * xx_total) - (x_total * x_total);

    a = ((num * xy_total) - (x_total * y_total)) / denominator;
    b = ((xx_total * y_total) - (xy_total * x_total)) / denominator;
  }
}

#endif /* !QRK_LEAST_SQUARE_H */
