The idea
Suppose a continuous function changes sign between a andb. The intermediate value theorem tells us that at least one real root lies between them. Bisection evaluates the midpoint and discards the half-interval that cannot contain the sign change.
Each successful iteration cuts the width of the bracket in half. Aftern steps, the surviving interval is only(b − a) / 2^n wide. That makes the method slower than some alternatives, but unusually transparent: the computation carries its own error bound around with it.
What bisection buys you: if the starting interval really brackets a sign change and the function is continuous, the method does not need a clever initial guess or a derivative. It just keeps making the uncertainty smaller.
bisection <- function(f, a, b, tol = 1e-3, m = 100) {
iter <- 0
f.a <- f(a)
f.b <- f(b)
while (abs(b - a) > tol) {
iter <- iter + 1
if (iter > m) {
warning("iterations maximum exceeded")
break
}
xmid <- (a + b) / 2
ymid <- f(xmid)
if (f.a * ymid > 0) {
a <- xmid
f.a <- ymid
} else {
b <- xmid
f.b <- ymid
}
}
root <- (a + b) / 2
return(root)
}