Golden Section Method

Im trying to write a golden section method function which finds the maximum of a function, g. Here is my r code;
golden <- function(g, a, b, epsilon){
e = 1 + ((sqrt(5)+1)/2)
w = a + (a + b)/e
v = b - (a + b)/e
while (abs(b-a) > epsilon){
if (g(w) > g(v)){
z <- b
v <- z - (a + z)/e
}else {
x <- a
w <- x + (x + b)/e
}
}
if ( g(v) < g(w)){
p = c(w, g(w))
return(p)
}else {
k = c(v, g(v))
return(k)
}
}

when i try golden(sin, 0, pi, 10^(-4)) r cannot terminate an answer as if it is taking too long. Does anybody know what is wrong with it?

The value of abs(b-a) > epsilon never changes.

what do i put below the if and else statements to fix this?

I don't know since I'm not sure what your code is trying to do, but the expression you use in the while statement should change as code gets executed. For example, if you replaced a and b by v and w, but then I'm not sure the code will achieve what you want. To find that out, you'd probably need to refer to the resources that inspired your code in the first place.

yes im trying to replace b with v or a with w so then the while statement would be v-a or b-w > epsilon. Also the statements below the while statement would have a replaced for w or b replaced for v but im guessing it isnt doing this and its just keeping a and b the same

golden <- function(g, a, b, epsilon){
e = 1 + ((sqrt(5)+1)/2)
while (abs(b-a) > epsilon){
w = a + (a + b)/e
v = b - (a + b)/e
if (g(w) > g(v)){
b <- v
}else {
a <- w
}
}
if ( g(v) < g(w)){
p = c(w, g(w))
return(p)
}else {
k = c(v, g(v))
return(k)
}
}

This might be better but has the same problem

Have you tried running debug(golden) before running golden(sin, 0, pi, 10^(-4))? That might show you what could be preventing it from stopping.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.