/****************************************************************************** * This program computes the roots of cubic equations * of the form Ax^3 + Bx^2 + Cx + D = 0 * * Copyright © 2020 Richard Lesh. All rights reserved. *****************************************************************************/ import org.pureprogrammer.Utils; public class CubicRoots { static final double A = 1.0; static final double B = -6.0; static final double C = 11.0; static final double D = -6.0; public static void main(String[] args) { /****************************************************************************** * General cubic can be changed to a depressed cubic * t^3 + pt + q = 0 * by substituting * x = t - B / 3A *****************************************************************************/ double p = (3. * A * C - B * B) / (3. * A * A); double q = (2. * B * B * B - 9. * A * B * C + 27. * A * A * D) / (27. * A * A * A); /****************************************************************************** * Roots of the depressed cubic are... * tk = a cos(b - 2πk/3) for k = 0, 1, 2 * with a = 2 sqrt(-p/3) * b = (1/3) arccos(3q/2p * sqrt(-3/p)) *****************************************************************************/ double a = 2. * Math.sqrt(-p / 3.); double b = (1. / 3.) * Math.acos(3. * q / 2. / p * Math.sqrt(-3. / p)); double t1 = a * Math.cos(b); double t2 = a * Math.cos(b - 2. * Math.PI / 3.); double t3 = a * Math.cos(b - 4. * Math.PI / 3.); double root1 = t1 - B / (3. * A); double root2 = t2 - B / (3. * A); double root3 = t3 - B / (3. * A); System.out.println(Utils.join("", "root #1: ", root1)); System.out.println(Utils.join("", "root #2: ", root2)); System.out.println(Utils.join("", "root #3: ", root3)); } }