bisection
my example
by SunnyHsu
JavaScript
// function declaration
function f(x) {
return Math.sin (x) - 0.5*x;
}
/*
// function expression
var f = function (x) {
return Math.sin (x) - 0.5*x;
};
*/
function ff(x) {
return Math.cos(x) - 0.33*x;
}
function bisection (func, xLo, xHi, eps) {
if (func(xLo) * func (xHi) > 0)
return undefined;
var xMid, fHi, fLo, fMid;
fHi = func(xHi); // fb
fLo = func(xLo); // fa
var iter = 0;
while (xHi - xLo > eps) {
++iter;
xMid = (xLo+xHi)/2;
fMid = func(xMid); // fc
//console.log ('f(c) = ' + fMid);
if (Math.abs(fMid) < eps)
return [xMid, iter];
else if (fMid*fLo < 0) { // fa*fc < 0 --> [a,c]
xHi = xMid;
fHi = fMid;
} else { // fc*fb < 0 --> [c,b]
xLo = xMid;
fLo = fMid;
}
}
return [(xLo+xHi)/2, iter];
}
var ans = bisection (ff, 1, 3, 1e-4);
alert ('in ' + ans[1] + ' iterations: ' + 'f(' + ans[0].toFixed(3) + ')= ' + ff(ans[0]).toExponential(3));
console.log('in ' + ans[1] + ' iterations: ' + 'f(' + ans[0].toFixed(3) + ')= ' + ff(ans[0]).toExponential(3));