@Test(expectedExceptions = IllegalArgumentException.class) public void testNull() { FINDER.getRoots(null); }
@Override public Double[] getRoots(RealPolynomialFunction1D function) { ArgChecker.notNull(function, "function"); double[] coefficients = function.getCoefficients(); if (coefficients.length != 4) { throw new IllegalArgumentException("Function is not a cubic"); } ComplexNumber[] result = ROOT_FINDER.getRoots(function); List<Double> reals = new ArrayList<>(); for (ComplexNumber c : result) { if (DoubleMath.fuzzyEquals(c.getImaginary(), 0d, 1e-16)) { reals.add(c.getReal()); } } ArgChecker.isTrue(reals.size() > 0, "Could not find any real roots"); return reals.toArray(EMPTY_ARRAY); }
@Test public void test() { try { FINDER.getRoots(null); Assert.fail(); } catch (final IllegalArgumentException e) { // Expected } try { FINDER.getRoots(new RealPolynomialFunction1D(1., 2., 3., 4.)); Assert.fail(); } catch (final IllegalArgumentException e) { // Expected } try { FINDER.getRoots(new RealPolynomialFunction1D(12., 1., 12.)); Assert.fail(); } catch (final MathException e) { // Expected } final Double[] roots = FINDER.getRoots(F); assertEquals(roots[0], -4.0, EPS); assertEquals(roots[1], -3.0, EPS); } }
@Test public void test() { final double[] r = new double[] {-RANDOM.nextDouble(), -RANDOM.nextDouble(), RANDOM.nextDouble(), RANDOM.nextDouble() }; final double a0 = r[0] * r[1] * r[2] * r[3]; final double a1 = r[0] * r[1] * r[2] + r[0] * r[1] * r[3] + r[0] * r[2] * r[3] + r[1] * r[2] * r[3]; final double a2 = r[0] * r[1] + r[0] * r[2] + r[0] * r[3] + r[1] * r[2] + r[1] * r[3] + r[2] * r[3]; final double a3 = r[0] + r[1] + r[2] + r[3]; final double a4 = 1; final RealPolynomialFunction1D f = new RealPolynomialFunction1D(new double[] {a0, a1, a2, a3, a4 }); final Double[] roots = FINDER.getRoots(f); Arrays.sort(roots); final double[] expected = new double[r.length]; for (int i = 0; i < r.length; i++) { expected[i] = -r[i]; } Arrays.sort(expected); for (int i = 0; i < roots.length; i++) { assertEquals(roots[i], expected[i], 1e-12); } } }