PolynomialCurveFitter extends AbstractCurveFitter { public static PolynomialCurveFitter create(int degree) { return new PolynomialCurveFitter(new double[degree + 1], Integer.MAX_VALUE); } private  PolynomialCurveFitter(double[] initialGuess,
                                  int maxIter); static PolynomialCurveFitter create(int degree); PolynomialCurveFitter withStartPoint(double[] newStart); PolynomialCurveFitter withMaxIterations(int newMaxIter);  }
@Test public void testNoError() { final Random randomizer = new Random(64925784252l); for (int degree = 1; degree < 10; ++degree) { final PolynomialFunction p = buildRandomPolynomial(degree, randomizer); final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(degree); final WeightedObservedPoints obs = new WeightedObservedPoints(); for (int i = 0; i <= degree; ++i) { obs.add(1.0, i, p.value(i)); } final PolynomialFunction fitted = new PolynomialFunction(fitter.fit(obs.toList())); for (double x = -1.0; x < 1.0; x += 0.01) { final double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); Assert.assertEquals(0.0, error, 1.0e-6); } } }
@Test public void testSmallError() { final Random randomizer = new Random(53882150042l); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { final PolynomialFunction p = buildRandomPolynomial(degree, randomizer); final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(degree); final WeightedObservedPoints obs = new WeightedObservedPoints(); for (double x = -1.0; x < 1.0; x += 0.01) { obs.add(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final PolynomialFunction fitted = new PolynomialFunction(fitter.fit(obs.toList())); for (double x = -1.0; x < 1.0; x += 0.01) { final double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.1); } } Assert.assertTrue(maxError > 0.01); }
@Test public void testLargeSample() { final Random randomizer = new Random(0x5551480dca5b369bl); double maxError = 0; for (int degree = 0; degree < 10; ++degree) { final PolynomialFunction p = buildRandomPolynomial(degree, randomizer); final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(degree); final WeightedObservedPoints obs = new WeightedObservedPoints(); for (int i = 0; i < 40000; ++i) { final double x = -1.0 + i / 20000.0; obs.add(1.0, x, p.value(x) + 0.1 * randomizer.nextGaussian()); } final PolynomialFunction fitted = new PolynomialFunction(fitter.fit(obs.toList())); for (double x = -1.0; x < 1.0; x += 0.01) { final double error = FastMath.abs(p.value(x) - fitted.value(x)) / (1.0 + FastMath.abs(p.value(x))); maxError = FastMath.max(maxError, error); Assert.assertTrue(FastMath.abs(error) < 0.01); } } Assert.assertTrue(maxError > 0.001); }