I am trying to write out the bisection function (
shows the iteration number is 0, I donot know how i can debug it, thank you for any help.
CodePudding user response:
Modifications to itera inside a function are done in the function's environment, not in the global environment.
You could pass itera as parameter to the function so that each recursive call increments its value:
bisect <- function(f, lower, upper, tol, itera=1)
{
mid <- (lower upper)/2
if(abs(f(mid)) < tol){
output <- list(root = mid, f.root = f(mid), iter = itera, estim.prec = abs(f(mid)))
return(output)
}
else{
itera = itera 1
if(f(mid) * f(lower) < 0){
bisect(f, lower, mid, tol,itera)
}
else{
bisect(f, mid, upper, tol,itera)
}
}
}
f <- function(x) {x^3 - 2*x - 1}
bisect(f,1,2,10^(-6))
$root
[1] 1.618034
$f.root
[1] -6.01767e-07
$iter
[1] 21
$estim.prec
[1] 6.01767e-07
Another option is to modify itera value in calling environment using <<- operator :
itera <- 1
bisect <- function(f, lower, upper, tol)
{
mid <- (lower upper)/2
if(abs(f(mid)) < tol){
output <- list(root = mid, f.root = f(mid), iter = itera, estim.prec = abs(f(mid)))
return(output)
}
else{
itera <<- itera 1
if(f(mid) * f(lower) < 0){
bisect(f, lower, mid, tol)
}
else{
bisect(f, mid, upper, tol)
}
}
}
$root
[1] 1.618034
$f.root
[1] -6.01767e-07
$iter
[1] 21
$estim.prec
[1] 6.01767e-07
f <- function(x) {x^3 - 2*x - 1}
bisect(f,1,2,10^(-6))
