Numerical Methods
quadratic equation
by joe chan
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;
return [x1,x2];
} else {
return [];
}
}
// (p1-p2)*y+(q2-q1)*x-p1*q2+p2*q1 = 0
function slovePoint(a1,b1,c1,a2,b2,c2){
var x,y;
x=(b2*c1-b1*c2)/(a2*b1-a1*b2);
y=-(a2*c1-a1*c2)/(a2*b1-a1*b2);
return [x,y]
}
// x=(b2*c1-b1*c2)/(a2*b1-a1*b2),y=-(a2*c1-a1*c2)/(a2*b1-a1*b2)
var roots = solve (1,2,-3);
//console.log (roots);
if (roots.length === 0)
console.log ('no real roots');
else
console.log ('x1: ' + roots[0] + '; ' +
'x2: ' + roots[1]);
var point = slovePoint(1,0,1,1,1,-2) ;
// x=-1 ; x+y = 2 x=-1 y=3
console.log(point);