Skip to Content

Implementation of golden section search for extremum in R

How can we modified this code to more efficient one and search until a tolerance level is reached for p1-p2 and in result we get the extremum value? Is there any faster algorithm for finding the extremum than this golden section serach ?

    lambda<-(sqrt(5)-1)/2
 
    golden.section<-function(f, pL, pU, p1, p2, top, result){
      if (top==26){
       return(result)
    }
    else if(top==1){
    p1<-pL + (1-lambda)*(pU - pL)
    p2<-pU - (1-lambda)*(pU - pL)
    } 
    result[top,]<-c(p1,p2)
    if(f(p2) < f(p1)){
    pU<-p2
    pL<-pL
    p2<-p1
    p1<-pL + (1-lambda)*(pU - pL)
    } else if (f(p2) > f(p1)){
    pU <- pU
    pL <- p1
    p1 <- p2
    p2<-pU - (1-lambda)*(pU - pL)
   }
   result<-golden.section(f, pL, pU, p1, p2, top=top+1, result)
   return(result)
   }
 
 result<-data.frame(p1=rep(NA, 25), p2=rep(NA, 25))
 result<-golden.section(function(x) -(x - 1.235)^2 + 0.78 * x + 0.2,
                   -5, 5, NA, NA, 1, result)