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?