This tutorial explains how to find the square root of a number in JavaScript. In JavaScript, we use JavaScript if...else Statement JavaScript Math sqrt()
Standard Form
The standard form of a quadratic equation is:
ax2 + bx + c = 0
where a, b and c are real numbers and a ≠ 0
To find the roots of such equation, we use the formula,
(root1,root2) = (-b ± √b^2-4ac)/2a
The discriminant of the quadratic equation is D = b2 - 4ac
For D > 0 the roots are real and distinct.
For D = 0 the roots are real and equal.
For D < 0 the roots do not exist, or the roots are imaginary.
Example
let quadEquation = function (a, b, c) {
let discriminant = Math.sqrt( (b * b) - (4 * a * c) );
let denom = 2 * a;
let firstRoot,secondRoot;
if (discriminant>0){
firstRoot = (-b + discriminant)/denom;
secondRoot = (-b - discriminant)/denom;
}
else if (discriminant == 0){
firstRoot = secondRoot = -b/denom;
}
else{
let real = (-b / denom ).toFixed(2);
let imag = (Math.sqrt(-discriminant) / denom ).toFixed(2);
let firstRoot = `${real} + ${imag}i`
let secondRoot = `${real} - ${imag}i`
}
console.log("The first root is " + firstRoot);
console.log("The second root is " + secondRoot);
};
quadEquation(5,6,1)
Output
The first root is -0.2
The second root is -1