- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding roots of a quadratic equation – JavaScript
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 ]
Advertisements