01: package JSci.tests;
02:
03: import JSci.maths.*;
04: import JSci.maths.polynomials.*;
05:
06: /**
07: * Testcase for polynomials.
08: */
09: public class PolynomialTest extends junit.framework.TestCase {
10: private final int n = 15;
11:
12: public static void main(String arg[]) {
13: junit.textui.TestRunner.run(PolynomialTest.class);
14: }
15:
16: public PolynomialTest(String name) {
17: super (name);
18: }
19:
20: protected void setUp() throws Exception {
21: JSci.GlobalSettings.ZERO_TOL = 1.0e-6;
22: super .setUp();
23: }
24:
25: private static double[] createRandomArray(int n) {
26: double[] arr = new double[n];
27: for (int i = 0; i < arr.length; i++)
28: arr[i] = 2.0 * Math.random() - 1.0;
29: return arr;
30: }
31:
32: public void testSubtract() {
33: RealPolynomial p = new RealPolynomial(createRandomArray(n));
34: p = (RealPolynomial) p.subtract(p);
35: assertEquals(RealPolynomialRing.getInstance().zero(), p);
36: assertEquals(0, p.degree());
37: }
38:
39: public void testLeastSquaresFit() {
40: // generate random polynomial
41: RealPolynomial p = new RealPolynomial(createRandomArray(n));
42:
43: // generate random sample data
44: final double scale = 10.0;
45: double[][] data = new double[2][n];
46: data[0][0] = scale * Math.random();
47: data[1][0] = p.map(data[0][0]);
48: for (int k = 1; k < data[0].length; k++) {
49: data[0][k] = data[0][k - 1] + scale * Math.random();
50: data[1][k] = p.map(data[0][k]);
51: }
52: RealPolynomial fitted = LinearMath.leastSquaresFit(n - 1, data);
53: assertEquals(p, fitted);
54: }
55:
56: public void testInterpolation() {
57: // unstable at large n
58: final int n = 5;
59: // generate random sample data
60: final double scale = 10.0;
61: double[][] data = new double[2][n];
62: data[0][0] = scale * Math.random();
63: data[1][0] = scale * Math.random();
64: for (int k = 1; k < data[0].length; k++) {
65: data[0][k] = data[0][k - 1] + scale * Math.random();
66: data[1][k] = scale * Math.random();
67: }
68:
69: RealPolynomial p = PolynomialMath.interpolateLagrange(data);
70: for (int k = 0; k < n; k++) {
71: assertEquals(data[1][k], p.map(data[0][k]),
72: JSci.GlobalSettings.ZERO_TOL);
73: }
74: }
75: }
|