Hello there. This page is on using R to find approximate roots with the bisection method.

You may want to refer to my page on The Bisection Method for more details.

**Sections**

What Is The Bisection Method? (Brief)

**What Is The Bisection Method? (Brief)**

The Bisection Method belongs to a class of numerical methods found in applied/computational mathematics. There are cases when the exact answer to a question cannot be found. Approximate solutions (with a small acceptable margin of error) are used instead.

**The Bisection Method In R**

In my R code, I define a few functions as examples. I have the functions as , and .

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Bisection Method In R: # References: http://www.dummies.com/programming/r/how-to-use-functions-as-arguments-in-r/ # Tim Sauer - Numerical Analysis Second Edition funct_1 <- function(x){ return(x^2 - 7) } funct_2 <- function(x){ return(x^2 - 5) } funct_3 <- function(x){ return(exp(x) - 2) } |

In the bisection method function, I have the inputs as a, b from the interval [a, b], the tolerance (margin of error allowed) represented by tol and the function f. (I have f = funct_1 by default.)

The output from the bisection method would be the approximate solution to the function. This approximate solution would be off from the exact solution by less than the tolerance.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Inputs: x, a and b in interval [a, b] and a function f. bisection_method <- function(a, b, tol, f = funct_1){ if (f(a)*f(b) > 0){ print("No root found.") } else while ((b - a)/2.0 > tol){ midpt= (a + b)/2.0 if (f(midpt) == 0){ return(midpt) #The midpoint is the x-intercept/root. } else if (f(a)*f(midpt) < 0){ # Increasing but below 0 case b = midpt } else a = midpt } return(midpt) } |

**Some Examples**

After defining the functions into R, function calls can be made. Here are some outputs from the bisection method.

1 2 3 4 5 6 7 8 |
> bisection_method(a = -1, b = 3, tol = 0.0001) # sqrt(7) [1] 2.64563 > > bisection_method(a = -1, b = 3, tol = 0.0001, f = funct_2) # sqrt(5) [1] 2.235962 > > bisection_method(a = -1, b = 3, tol = 0.0001, f = funct_3) #ln(2) which is about 0.693 [1] 0.6932373 |

**References**

- http://www.dummies.com/programming/r/how-to-use-functions-as-arguments-in-r/
- Tim Sauer – Numerical Analysis Second Edition