As part of a program I\'m writing, I need to solve a cubic equation exactly (rather than using a numerical root finder):
a*x**3 + b*x**2 + c*x + d = 0.
Here's A. Rex's solution in JavaScript:
a = 1.0;
b = 0.0;
c = 0.2 - 1.0;
d = -0.7 * 0.2;
q = (3*a*c - Math.pow(b, 2)) / (9 * Math.pow(a, 2));
r = (9*a*b*c - 27*Math.pow(a, 2)*d - 2*Math.pow(b, 3)) / (54*Math.pow(a, 3));
console.log("q = "+q);
console.log("r = "+r);
delta = Math.pow(q, 3) + Math.pow(r, 2);
console.log("delta = "+delta);
// here delta is less than zero so we use the second set of equations from the article:
rho = Math.pow((-Math.pow(q, 3)), 0.5);
theta = Math.acos(r/rho);
// For x1 the imaginary part is unimportant since it cancels out
s_real = Math.pow(rho, (1./3.)) * Math.cos( theta/3);
t_real = Math.pow(rho, (1./3.)) * Math.cos(-theta/3);
console.log("s [real] = "+s_real);
console.log("t [real] = "+t_real);
x1 = s_real + t_real - b / (3. * a);
console.log("x1 = "+x1);
console.log("should be zero: "+(a*Math.pow(x1, 3)+b*Math.pow(x1, 2)+c*x1+d));