01: import java.awt.*;
02: import java.awt.event.*;
03: import JSci.awt.*;
04: import JSci.maths.*;
05: import JSci.maths.polynomials.RealPolynomial;
06:
07: /**
08: * Sample program demonstrating use of LinearMath.leastSquaresFit method
09: * and the LineTrace graph class.
10: * @author Mark Hale
11: * @version 1.0
12: */
13: public final class CurveFitter extends Frame {
14: private Label fnLabel = new Label("P(x) = ?", Label.CENTER);
15: private LineTrace graph = new LineTrace(-10.0f, 10.0f, -10.0f,
16: 10.0f);
17: private TextField polyDegreeField = new TextField("4");
18: private Button fitButton = new Button("Fit");
19: private Button clearButton = new Button("Clear");
20:
21: public static void main(String arg[]) {
22: new CurveFitter();
23: }
24:
25: public CurveFitter() {
26: super ("Curve Fitter");
27: addWindowListener(new WindowAdapter() {
28: public void windowClosing(WindowEvent evt) {
29: dispose();
30: System.exit(0);
31: }
32: });
33: fitButton.addActionListener(new ActionListener() {
34: public void actionPerformed(ActionEvent evt) {
35: fitCurve();
36: }
37: });
38: clearButton.addActionListener(new ActionListener() {
39: public void actionPerformed(ActionEvent evt) {
40: graph.clear();
41: }
42: });
43: add(fnLabel, "North");
44: add(graph, "Center");
45: Panel buttonPanel = new Panel();
46: buttonPanel.add(new Label("Polynomial degree:"));
47: buttonPanel.add(polyDegreeField);
48: buttonPanel.add(fitButton);
49: buttonPanel.add(clearButton);
50: add(buttonPanel, "South");
51: setSize(500, 400);
52: setVisible(true);
53: }
54:
55: private void fitCurve() {
56: Graph2DModel model = graph.getModel();
57: model.firstSeries();
58: double data[][] = new double[2][model.seriesLength()];
59: for (int i = 0; i < data[0].length; i++) {
60: data[0][i] = model.getXCoord(i);
61: data[1][i] = model.getYCoord(i);
62: }
63: int degree = Integer.parseInt(polyDegreeField.getText());
64: RealPolynomial poly = LinearMath.leastSquaresFit(degree, data);
65: fnLabel.setText(poly.toString());
66: }
67: }
|