Computing zeroes (solutions) of a mathematical equation in 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.

Example

The code for this will be −

const coeff = [1, 12, 3];
const findRoots = co => {
   const [a, b, c] = co;
   const discriminant = (b * b) - 4 * a * c;
   // non real roots
   if(discriminant < 0){
      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(coeff));

Output

The output in the console −

[ -0.2554373534619714, -11.744562646538029 ]
raja
Published on 17-Oct-2020 09:00:44
Advertisements