/***************************************************************** JamaFit.java use JAMA Matrix library for least squares parabola fit R.H. Landau, Oregon State Univ., 2002 y(x) = b0 + b1 x + b2 x^2 http://math.nist.gov/javanumerics/jama JAMA library must be in same directory or modify CLASSPATH variable to include JAMA directory uses Matrix class, i.e. Matrix as object //*****************************************************************/ import Jama.*; import java.io.*; public class JamaFit { public static void main(String[] argv) { // The data as three vectors: // double [] x = {1., 1.05, 1.15, 1.32, 1.51, 1.68, 1.92}; double [] y = {0.52, 0.73, 1.08, 1.44, 1.39, 1.46, 1.58}; double [] sig = {0.1, 0.1, 0.2, 0.3, 0.2, 0.1, 0.1}; int Nd = 7; // Number of data points double sig2, s,sx,sxx,sy,sxxx,sxxxx,sxy,sxxy, rhl; // // Create 3x3 Java array for A matrix = Sx, X and B use Matrix class only // double [][] Sx = new double[3][3]; // Generate matrix elements via for over data s= sx = sxx = sy = sxxx = sxxxx = sxy = sxy = sxxy = 0; for (int i=0; i <= Nd-1; i++) { sig2 = sig[i]*sig[i]; s += 1./sig2; sx += x[i]/sig2; sy += y[i]/sig2; rhl = x[i]*x[i]; sxx += rhl/sig2; sxxy += rhl*y[i]/sig2; sxy += x[i]*y[i]/sig2; sxxx += rhl*x[i]/sig2; sxxxx += rhl*rhl/sig2; } // Load array Sx with symmetry Sx[0][0] = s; Sx[0][1] = Sx[1][0] = sx; Sx[0][2] = Sx[2][0] = Sx[1][1] = sxx; Sx[1][2] = Sx[2][1] = sxxx; Sx[2][2] = sxxxx; // Form matrix MatSx for Matrix Class from 2D array Sx Matrix MatSx = new Matrix(Sx); // Form Matrix Sy with Jama set command Matrix MatSy = new Matrix(3,1); MatSy.set(0,0,sy); MatSy.set(1,0,sxy); MatSy.set(2,0,sxxy); // Solve matrix equation for B via inverse & test inverse Matrix B = MatSx.inverse().times(MatSy); Matrix Itest = MatSx.inverse().times(MatSx); // Print out entire matrices using Jama print System.out.print( "B Matrix via inverse" ); B.print (16,14); System.out.print( "MatSx.inverse().times(MatSx) " ); Itest.print (16,14); // Solve matrix equation directly for B B = MatSx.solve(MatSy); System.out.print( "B Matrix via direct" ); B.print (16,14); // Extract parabola parameters using Jama get System.out.println( "y(x) = b0 + b1 x + b2 x^2 " ); System.out.println( " " ); System.out.println(" b0 = " + B.get(0,0) ); System.out.println(" b1 = " + B.get(1,0) ); System.out.println(" b2 = " + B.get(2,0) ); System.out.println( " " ); //test fit and oprint out for (int i=0; i <= Nd-1; i++) { s=B.get(0,0)+B.get(1,0)*x[i]+B.get(2,0)*x[i]*x[i]; System.out.println(" i, xi, yi, yfit = " +i+ ", "+ x[i] +", " +y[i]+", " + s ); } } } // End of file