Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding roots of a quadratic equation – JavaScript
A quadratic equation has the form ax² + bx + c = 0, where a, b, and c are coefficients. To find the roots, we use the quadratic formula and check if the discriminant is non-negative for real roots.
Quadratic Formula
The quadratic formula is:
x = (-b ± ?(b² - 4ac)) / (2a)
The discriminant (b² - 4ac) determines the nature of roots:
- If discriminant > 0: Two distinct real roots
- If discriminant = 0: One repeated real root
- If discriminant
Example
Here's a JavaScript function that finds the real roots of a quadratic equation:
const coefficients = [3, 12, 2];
const findRoots = co => {
const [a, b, c] = co;
const discriminant = (b * b) - 4 * a * c;
if(discriminant
[ -0.17425814164944628, -3.825741858350554 ]
Testing Different Cases
Let's test various scenarios:
// Two distinct real roots
console.log("Case 1: x² - 5x + 6 = 0");
console.log(findRoots([1, -5, 6]));
// One repeated root
console.log("\nCase 2: x² - 6x + 9 = 0");
console.log(findRoots([1, -6, 9]));
// No real roots
console.log("\nCase 3: x² + 2x + 5 = 0");
console.log(findRoots([1, 2, 5]));
Case 1: x² - 5x + 6 = 0
[ 3, 2 ]
Case 2: x² - 6x + 9 = 0
[ 3, 3 ]
Case 3: x² + 2x + 5 = 0
false
Enhanced Version with Root Type Information
const findRootsDetailed = (a, b, c) => {
const discriminant = (b * b) - 4 * a * c;
if (discriminant
{ type: 'distinct', roots: [ 3, 2 ] }
{ type: 'repeated', roots: [ 3, 3 ] }
{ type: 'complex', roots: null }
Conclusion
The quadratic formula efficiently finds real roots by calculating the discriminant first. This approach avoids complex number calculations when only real roots are needed, returning false for equations with no real solutions.
Advertisements
