JSFiddle - React, Tailwind, and code Playground
by zakariamouhid
JavaScript
function solve(a, b, c, d) {
// ax^3 + bx^2 + cx + d = 0
"use strict";
if (a === 0) {
// bx^2 + cx + d = 0
if (b === 0) {
// cx + d = 0
if (c === 0) {
// d = 0
if (d === 0) {
return 0;
}
return false;
}
return -d / c;
}
return (function (a, b, c) {
var dilta = b * b - 4 * a * c;
if (dilta < 0) {return false; }
return (-b + Math.sqrt(dilta)) / (2 * a);
})(b, c, d);
}
var A = b / a,
B = c / a,
C = d / a,
p = B - A * A / 3,
q = 2 * A * A * A / 27 - A * B / 3 + C,
dilta = q * q + 4 * p * p * p / 27,
fi,
x0;
if (dilta >= 0) {
x0 = -Math.cbrt((q + Math.sqrt(dilta)) / 2) + Math.cbrt((Math.sqrt(dilta) - q) / 2) - A / 3;
} else {
fi = Math.acos(-q * Math.pow(-3 / p, 3 / 2) / 2);
x0 = 2 * Math.sqrt(- p / 3) * Math.cos(fi / 3) - A / 3;
}
return x0;
}
function f(x, a, b, c, d) {
"use strict";
return a * x * x * x + b * x * x + c * x + d;
}
var x0 = solve(1, -2, -2, -3),
fx0 = f(x0, 1, -2, -2, -3);
document.body.innerHTML = "x0 = " + x0 + "<br>f(x0) = " + fx0;
/*
(x - 3)(x^2 + x + 1) = 0
x^3 + x^2 + x - 3x^2 - 3x - 3 = 0
x^3 - 2x^2 - 2x - 3 = 0
*/