Solution

ID: past-exam-of-the-probability-statistics-and-options-i-course-of-the-university-of-oxford/2011/u/1/b/solution

The following R function uses the factored polynomial for evaluation, handles endpoint and midpoint roots, and returns a midpoint only once its error bound is at most eps:
bisect <- function(a, b, eps = 1e-8, maxiter = 1000L) {
  f <- function(x) x * (x - 1) * (x - 2) * (x - 5)
  stopifnot(length(a) == 1L, length(b) == 1L,
            is.finite(a), is.finite(b), a < b,
            length(eps) == 1L, is.finite(eps), eps > 0)
  fa <- f(a)
  fb <- f(b)
  if (fa == 0) return(a)
  if (fb == 0) return(b)
  if (sign(fa) == sign(fb)) stop("Endpoints must bracket a sign change")
  for (i in seq_len(maxiter)) {
    m <- a + (b - a) / 2
    fm <- f(m)
    if (fm == 0 || (b - a) / 2 <= eps) return(m)
    if (sign(fm) == sign(fa)) {
      a <- m
      fa <- fm
    } else {
      b <- m
    }
  }
  stop("Iteration limit reached")
}
Each update preserves the sign-changing bracket, and the stopping bound is the half-width of that bracket. Thus continuity and the intermediate value theorem justify the returned root approximation.

New to topics? Read the docs here!