/* * Code for fitLine * with self-test main routine * * @author Chee Yap * Basic Algorithms, Fall 2005 */ import java.math.*; import java.util.Random; public class fitLine { // scalar product of two vectors: static double scalar (double[] X, double[] Y) { double s = 0; for (int i=0; i< X.length; i++) s += X[i]* Y[i]; return s; } // computes a 2x2 matrix based on 2 input basis vectors (phi0, phi1): static double[][] matrix (double[] phi0, double[] phi1) { double[][] m = new double[2][2]; m[0][0] = scalar(phi0, phi0); m[0][1] = m[1][0] = scalar(phi0, phi1); m[1][1] = scalar(phi1, phi1); return m; } // computes determinant of a 2x2 matrix: static double det (double[][] m) { return (( m[0][0]*m[1][1] ) - ( m[0][1]* m[1][0] )); } /** * fitLine computes the least squares best fit line (a+bX) for a function * where the (discrete) function is given by lX and lY * @param lX is a vector of some length n * @param lY is a vector of the same length n * @returns [a,b] representing the the least-squares line (a+bX) */ public static double[] fitLine(double[] lX, double [] lY) { int n = lX.length; double[] l1 = new double[n]; for (int i=0; i