I tried to implement a simple bisection algorithm using recursion. I thought it worked but then i wanted to test its efficiency against using while loop.
For some reason, the recursion stops before the condition is met, while the while loop (pun intended) does what i would expect.
When trying to bisect x/2 untill x==0 (the very limit of the computer basically), its tops at value of x = 0.003051758
Code:
# Trying to compare between recursion and while methods of bisection in terms of efficiency
# However the recursion method behaves in an unexpected way
# install.packages("tictoc")
# Mehod 1: recursion
bisect <- function(x,epsilon=0){
while(x>epsilon){
cat(x/2,"\n")
return(bisect(x/2))
}
return(x)
}
# Method 2: while
bisectwhile <- function(x,epsilon=0){
while(x>epsilon){
x <- x/2
print(x)
}
return(x)
}
N <- 100
# M1
tictoc::tic()
bisect(N)
tictoc::toc()
#50
#25
#.
#.
#.
#0.003051758
#[1] 0.003051758
# M2
tictoc::tic()
bisectwhile(N)
tictoc::toc()
A loop is faster than recursion here:
If you want to display all the values, try:
Both of which end up at 0, as you can see:
Created on 2023-03-06 with reprex v2.0.2