Bisection method of finding a root in R

I wrote this code in R for the Bisection method

Bisection <- function(xL, xR, eps, max_iter){
iter <- 1
while ((abs(xR-xL) > eps) && (iter > max_iter)){
  xM <- (xL+xR)/2
  if (f(xM)*f(xR) < 0){
    xL <- xM
  }else{
    xR <- xM
  }
  iter <- iter +1
}

Form some function f(x) which you can fill in by yourself. However, I have the idea that it is not working how it should do. Does anybody see a mistake?

Upvotes: 1

Views: 1312

Answers (1)

peterweethetbeter
peterweethetbeter

Reputation: 21

I think your code is fine except for a few minor mistakes. (iter > max_iter) should ofcourse be (iter < max_iter). Furthermore, you have not specified a function f(). See my code below for an example of a working algorithm. Once can use the f.acc function to find a xL and xR and if the function is continuous,it must have a root in between.

f.acc <- function(x){
  1+1/x-log(x)
}
xL<- 0.5
xR <- 6
eps <- 1e-6
max_iter <- 100
iter <- 1
  while ((abs(xR-xL) > eps) && (iter < max_iter)){
    xM <- (xL+xR)/2
    if (f.acc(xM)*f.acc(xR) < 0){
      xL <- xM
    }else{
      xR <- xM
    }
    iter <- iter +1
    cat("At iteration", iter, "value of x.mid is:", x.mid, "\n")
  }

Upvotes: 1

Related Questions