Numerical Methods
quadratic equation
by zero3495
JavaScript
function solve (a,b,c) {
var x1, x2;
var d = b*b-4*a*c;
if (d >= 0) {
var sd = Math.sqrt(d);
x1 = (-b+sd)/2/a;
x2 = (-b-sd)/2/a;
// console.log (x1 + ', ' + x2);
return [x1,x2];
} else {
// no real roots
return [];
}
}
//
// from http://mathworld.wolfram.com/QuadraticEquation.html
//
function solveBetter (a,b,c) {
var x1, x2;
var d = b*b - 4*a*c;
if (d >= 0) {
var sgnB = b > 0 ? 1 : -1;
var q = -(b + sgnB*Math.sqrt(b*b - 4*a*c))/2;
x1 = q/a;
x2 = c/a/x1;
return [x1,x2];
} else {
// no real roots
return [0,0];
}
}
var roots = solveBetter (1,2,-3);
//console.log (roots);
if (roots.length === 0)
console.log ('no real roots');
else
console.log ('x1: ' + roots[0] + '; ' +
'x2: ' + roots[1]);