/*
 * Squares.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Numerical Computation'
 * section: `Least Squares Fits'
 *
 * This program using the least squares method to
 * fit a line to some data.
 */
public class Squares
{
  // The data to be fitted.
  public static final int N = 6;
  public static final double[] X =
    { 0.1, 3.7, 4.2, 6.3, 8.7, 9.8 };
  public static final double[] Y =
    { 6.0, 7.0, 7.2, 8.0, 9.3, 9.4 };


  // The `main' method actually implements
  // the least squares fit.
  public static void main(String[] argv)
  {
    int i;

    // Compute averages.
    double xbar = 0;
    for (i=0; i<N; i++)
      xbar += X[i];
    xbar /= N;

    double ybar = 0;
    for (i=0; i<N; i++)
      ybar += Y[i];
    ybar /= N;

    // Compute Sxx and Syy
    double Sxx = 0;
    for (i=0; i<N; i++)
      Sxx += (X[i] - xbar) * (X[i] - xbar);

    double Sxy = 0;
    for (i=0; i<N; i++)
      Sxy += (X[i] - xbar) * (Y[i] - ybar);

    // Hence find maximum likelihood
    // estimators.
    double a = Sxy / Sxx;
    double b = ybar - a * xbar;

    // Finally output some data about the fit.
    System.out.println("Line of best fit: y = "
                       + a + " * x + " + b);

    for (i=0; i<N; i++)
      System.out.println("At x = " + X[i]
                         + " would expect "
                         + (a * X[i] + b)
                         + " and measured "
                         + Y[i]);
  }
}

