bisection <- function(expr, x = c(0, 1), TOL = 1e-6, print = FALSE) { hasZero <- function(a, b, expr = expr) (eval(expr, envir = list(x = a), enclos = parent.frame()) * eval(expr, envir = list(x = b), enclos = parent.frame())) < 0 expr <- checkExpression(expr) if (length(x) != 2) stop("'x' should be a length-2 vector specifying an interval [a, b] containing root") a <- min(x) b <- max(x) d <- getOption("digits") if (!hasZero(a, b)) stop("Interval does not enclose root.") while ((b - a) / 2 > TOL) { c <- (a + b) / 2 if (print) print(sprintf("%.*f %.*f", d, c, d, (b - a) / 2), quote = FALSE) ifelse(hasZero(a, c), b <- c, a <- c) } # end while loop return(c) } # end bisection