QuadraticRootFinder { public static ImmutableList<Complex> find(double a, double b, double c) { if (a == 0) { Preconditions.checkArgument(b != 0, "No solutions can be found for an equation of the form c = 0"); return ImmutableList.of(new Complex(-c / b, 0)); } double discriminant = Math.pow(b, 2) - 4 * a * c; if (discriminant < 0) { Complex rootOne = new Complex(-b / (2 * a), Math.sqrt(-discriminant) / (2 * a)); Complex rootTwo = new Complex(rootOne.getReal(), -rootOne.getImaginary()); return ImmutableList.of(rootOne, rootTwo); } Complex rootOne = new Complex((-b + Math.sqrt(discriminant)) / (2 * a), 0d); Complex rootTwo = new Complex((-b - Math.sqrt(discriminant)) / (2 * a), 0d); return ImmutableList.of(rootOne, rootTwo); } private  QuadraticRootFinder(); static ImmutableList<Complex> find(double a, double b, double c);  }
@Test void find_whenBothRootsAreReal_thenReturnsCorrectRoots() { ImmutableList<Complex> roots = QuadraticRootFinder.find(2, -3, 1); ImmutableList<Pair<Double, Double>> expectedRoots = ImmutableList.of( Pair.of(1.0, 0.0), Pair.of(0.5, 0.0) ); assertEquals(expectedRoots, roots); }
@Test void find_whenBothRootsAreComplex_thenReturnsCorrectRoots() { ImmutableList<Complex> roots = QuadraticRootFinder.find(2, -3, 2); ImmutableList<Pair<Double, Double>> expectedRoots = ImmutableList.of( Pair.of(0.75, 0.6614), Pair.of(0.75, -0.6614) ); assertEquals(expectedRoots, roots); }
@Test void find_whenBothRootsAreEqual_thenReturnsCorrectRoots() { ImmutableList<Complex> roots = QuadraticRootFinder.find(2, 4, 2); ImmutableList<Pair<Double, Double>> expectedRoots = ImmutableList.of( Pair.of(-1.0, 0.0), Pair.of(-1.0, 0.0) ); assertEquals(expectedRoots, roots); }
@Test void find_whenGivenLinearEquation_thenReturnsCorrectRoot() { ImmutableList<Complex> roots = QuadraticRootFinder.find(0, 2, 1); ImmutableList<Pair<Double, Double>> expectedRoots = ImmutableList.of( Pair.of(-0.5, 0.0) ); assertEquals(expectedRoots, roots); }