I have tried implementing a method that can solve a quartic polynomial given a, b, c, d, e, using this method: https://math.stackexchange.com/a/786/127747
It works for some solutions were there are 1 or 2 real roots, but the problem is that, sometimes the square or cubic roots involved might cause NaN values to appear in the intermediate variables if they take negatives as input, for example Math.sqrt(-9)
, which then messes with the final answer, making all of the roots NaN in the end of the method.
Is there any fast analytical way to only get all real roots of a quartic polynomial in Java, given variables/coefficients a, b, c, d and e, which does not involve some Complex library etc?
Edit: (Any understandable language works, but preferably Java, and if that's not the case, I will anyways make a port, and edit the answer to append it)
Edit 2: Here is my current code, where s is p from the equation, and q are just variables to optimize it a little bit, so that the same calculations aren't done twice:
public static double[] solveRealQuarticRoots(double a, double b, double c, double d, double e) {
double s1 = 2 * c * c * c - 9 * b * c * d + 27 * (a * d * d + b * b * e) - 72 * a * c * e,
q1 = c * c - 3 * b * d + 12 * a * e;
s2 = s1 + Math.sqrt(-4 * q1 * q1 * q1 + s1 * s1),
q2 = Math.cbrt(s2 / 2),
s3 = q1 / (3 * a * q2) + q2 / (3 * a),
s4 = Math.sqrt((b * b) / (4 * a * a) - (2 * c) / (3 * a) + s3),
s5 = (b * b) / (2 * a * a) - (4 * c) / (3 * a) - s3,
s6 = (-(b * b * b) / (a * a * a) + (4 * b * c) / (a * a) - (8 * d) / a) / (4 * s4);
double[] roots = new double[4];
for (int i = 0; i < 3; i++)
roots[i] = -b / (4 * a) + (i > 1 ? -1 : 1) * (s4 / 2) - (i % 2 == 0 ? -1 : 1) * (Math.sqrt(s5 + (i > 1 ? -1 : 1) * s6) / 2);
return roots;
}