I need to do numerical root finding using bisection method, and print the values of variables involved at every iteration until it reaches a certain value.
bisection <- function(x1, x2){
l <- vector(mode="integer")
l[1] <- x1
r <- vector(mode="integer")
r[1] <- x2
m <- vector(mode="integer")
gl <- vector(mode="integer")
gr <- vector(mode="integer")
gm <- vector(mode="integer")
root <- 5e-8
i <- 1
repeat{
m[i] <- (l[i]+r[i])/2
gl[i] <- gx(l[i])
gr[i] <- gx(r[i])
gm[i] <- gx(m[i])
if (isTRUE(abs(gm[i]) > root) && isTRUE(gl[i]*gm[i] < 0)){
l[i+1] <- l[i]
r[i+1] <- m[i]
}
if (isTRUE(gm[i] > root) && isTRUE(gr[i]*gm[i] < 0)){
l[i+1] <- m[i]
r[i+1] <- r[i]
}
else if (isTRUE(abs(gm[i]) <= root)){
j <- c(0:(length(gm)-1))
df <- data.frame(j, l,r,m,gl,gr,gm)
names(df) <- c("i", "xl","xr","xm", "gxl","gxr", "gxm")
print(df)
break
}
}
}
When I try running this function with bisection(1,1.5)
, its output is only one row of iteration even tho solving for it manually would result in at least 12 iterations. It also hangs(?).
I don't know where I'm going wrong. Please help.
Edited to say the gx function is this: gx <- function(x){x^3-x-1}
There are two issues with your code:
if
statement you forgotabs
, it has to beif (isTRUE(abs(gm[i]) > root)
i
remains 1.Additionally I made a small adjustment to your code. Instead of using if-if-else-if first check wether the root is found and if not update l and r using one if-else. Makes it easier to read and understand.