Testing the Generic Class Library


Let's see how the generic and problem-specific parts work together by writing a simple test program. The LineDemo class loads data to be curve fit into arrays x[] and y[] . The data is to be fit to a straight line, so a Polynomial object representing a first-order polynomial is created by sending the value 1 to the Polynomial class constructor. The leastSquaresFit() method is then called with the Polynomial object and the x[] and y[] arrays as arguments.

The leastSquaresFit() method performs a least squares fit analysis on the data and computes the straight-line coefficients. The coefficients are listed as well as the value of the curve fit line when x = 0. The following is the LineDemo source code.

 import TechJava.MathLib.*; public class LineDemo {   public static void main(String args[]) {     double x[] = { 5.0, 10.0, 15.0, 20.0 };     double y[] = { 2281.9, 3205.3, 4302.5, 5445.0 };     //  Create a Polynomial object that represents a     //  straight line, y = Cx + D.     Polynomial straightLine = new Polynomial(1);     //  Curve fit the data to a straight line.     DataModeling.leastSquaresFit(straightLine, x, y);     //  Show the resulting curve-fit equation     double coeff[] = straightLine.getCoefficients();     System.out.println("y = " + coeff[0] + "x + " +                         coeff[1]);     //  Get the curve fit value at x=0.0     System.out.println();     System.out.println("x = 0.0 y = " +                         straightLine.getValue(0.0));   } } 

Output ”

 y = 211.729999999x + 1162.05 x = 0.0   y = 1162.05 

Figure 23.1 shows a plot of the original data and the computed curve fit. You can see that some data points are below the line and some are above, but the computed curve fit line does a good job representing the data. Another benefit of the curve fit line is it lets you estimate the intercept of the data, the value of y when x = 0.

Figure 23.1. Least squares curve fit

graphics/23fig01.gif

Since the Polynomial class can be used to represent any polynomial equation (and therefore is generic) you might wonder why we didn't incorporate the Polynomial class functionality into the leastSquaresFit() method. The answer is that the least squares fit process can be applied to types of equations other than polynomials , and other equation types will fill the arrays A T A and A T b in different ways. To maintain the integrity of the generic class library, it is necessary to represent the curve fit equation in a separate class. We will discuss how to model nonpolynomial equations in the next chapter.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net