Finding roots of a quadratic equation – JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in three numbers (representing the coefficient of quadratic term, coefficient of linear term and the constant respectively in a quadratic quadratic).

And we are required to find the roots, (if they are real roots) otherwise we have to return false. Let's write the code for this function

Example

Following is the code −

const coefficients = [3, 12, 2];
const findRoots = co => {
   const [a, b, c] = co;
   const discriminant = (b * b) - 4 * a * c;
   if(discriminant < 0){
      // the roots are non-real roots
      return false;
   };
   const d = Math.sqrt(discriminant);
   const x1 = (d - b) / (2 * a);
   const x2 = ((d + b) * -1) / (2 * a);
   return [x1, x2];
};
console.log(findRoots(coefficients));

Output

The output in the console −

[ -0.17425814164944628, -3.825741858350554 ]
raja
Published on 15-Sep-2020 14:51:57
Advertisements