Let's say you have an algebraic equation: x² − 7x + 12 = 0
.
Then, you can create a function as below:
function f(x) {
var y = x*x - 7*x + 12;
return y;
}
and then apply numerical methods:
var min=-100.0, max=100.0, step=0.1, diff=0.01;
var x = min;
do {
y = f(x);
if(Math.abs(y)<=diff) {
console.log("x = " + Math.round(x, 2));
// not breaking here as there might be multiple roots
}
x+=step;
} while(x <= max);
Above code scans for roots of that quadratic equation in range [-100, 100]
with 0.1
as a step.
The equation can also taken as user input (by constructing function f
using eval
function).
You can also use Newton-Raphson or other faster methods to solve algebraic equations in JavaScript.