1 package JSci.tests; 2 3 import JSci.maths.*; 4 import JSci.maths.polynomials.*; 5 6 9 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 public PolynomialTest(String name) { 16 super(name); 17 } 18 protected void setUp() throws Exception { 19 JSci.GlobalSettings.ZERO_TOL=1.0e-6; 20 super.setUp(); 21 } 22 private static double[] createRandomArray(int n) { 23 double[] arr = new double[n]; 24 for(int i=0; i<arr.length; i++) 25 arr[i] = 2.0*Math.random()-1.0; 26 return arr; 27 } 28 public void testSubtract() { 29 RealPolynomial p = new RealPolynomial(createRandomArray(n)); 30 p = (RealPolynomial) p.subtract(p); 31 assertEquals(RealPolynomialRing.getInstance().zero(), p); 32 assertEquals(0, p.degree()); 33 } 34 public void testLeastSquaresFit() { 35 RealPolynomial p = new RealPolynomial(createRandomArray(n)); 37 38 final double scale = 10.0; 40 double[][] data = new double[2][n]; 41 data[0][0] = scale*Math.random(); 42 data[1][0] = p.map(data[0][0]); 43 for ( int k = 1; k < data[0].length; k++ ) { 44 data[0][k] = data[0][k - 1] + scale*Math.random(); 45 data[1][k] = p.map(data[0][k]); 46 } 47 RealPolynomial fitted = LinearMath.leastSquaresFit(n-1, data); 48 assertEquals(p, fitted); 49 } 50 public void testInterpolation() { 51 final int n = 5; 53 final double scale = 10.0; 55 double[][] data = new double[2][n]; 56 data[0][0] = scale*Math.random(); 57 data[1][0] = scale*Math.random(); 58 for ( int k = 1; k < data[0].length; k++ ) { 59 data[0][k] = data[0][k - 1] + scale*Math.random(); 60 data[1][k] = scale*Math.random(); 61 } 62 63 RealPolynomial p = PolynomialMath.interpolateLagrange(data); 64 for ( int k = 0; k < n; k++ ) { 65 assertEquals(data[1][k], p.map(data[0][k]), JSci.GlobalSettings.ZERO_TOL); 66 } 67 } 68 } 69 70 | Popular Tags |