RootFinder.js
RootFinder.js is a lightweight JavaScript library for finding the roots of quadratic equations and cubic equations. It leverages the Complex.js library to handle complex solutions, ensuring precision and correctness when dealing with both real and complex numbers.
Features
- Solve quadratic equations of the form
ax2 + bx + c = 0. - Solve cubic equations of the form
ax3 + bx2 + cx + d = 0using Cardano's method. - Support for complex roots using
Complex.js.
Installation
You can install RootFinder.js via npm:
Or with yarn:
Alternatively, download or clone the repository:
Usage
Include the rootfinder.min.js file in your project:
<script src="path/to/complex.min.js">script>
<script>
const roots = RootFinder.quadratic(2, 5, 6);
...
script>
Or in a Node.js project:
or
Solving Quadratic Equations
To find the roots of a quadratic equation ax2 + bx + c = 0:
console.log(roots); // Output: [ Complex { re: 2 }, Complex { re: 1 } ]
If the equation has complex roots:
console.log(complexRoots); // Output: [ Complex { re: 0, im: 1 }, Complex { re: 0, im: -1 } ]
Solving Cubic Equations
To find the roots of a cubic equation ax3 + bx2 + cx + d = 0:
console.log(roots); // Output: [ Complex { re: 1 }, Complex { re: 2 }, Complex { re: 3 } ]
For cubic equations with complex roots:
console.log(complexRoots); // Output: [ Complex { re: 1, im: 0 }, Complex { re: -0.5, im: 0.866 }, Complex { re: -0.5, im: -0.866 } ]
API
quadratic(a, b, c[, returnReal=false])
Solves the quadratic equation ax2 + bx + c = 0.
-
Parameters:
a(Number): Coefficient ofx2b(Number): Coefficient ofxc(Number): Constant termreturnReal(optional Boolean): Decide if only real roots should be returned
-
Returns: An array of roots, which can contain real or complex numbers.
cubic(a, b, c, d[, returnReal=false])
Solves the cubic equation ax3 + bx2 + cx + d = 0 using Cardano's method.
-
Parameters:
a(Number): Coefficient ofx3b(Number): Coefficient ofx2c(Number): Coefficient ofxd(Number): Constant termreturnReal(optional Boolean): Decide if only real roots should be returned
-
Returns: An array of roots, which can contain real or complex numbers.
Coding Style
Like all my libraries, RootFinder.js is written to minimize size after compression with Google Closure Compiler in advanced mode. The code style is optimized to maximize compressibility. If you extend the library, please preserve this style.
Building the library
After cloning the Git repository run:
npm install
npm run build
Run a test
Testing the source against the shipped test suite is as easy as
npm run test
Copyright and Licensing
Copyright (c) 2025, Robert Eisele Licensed under the MIT license.