source("D:/FaraDars.org/T1365/FVR97041/source/codes/ch2/pr12.r")

line.search <- function(f, x, y, tol = 1e-9, a.mx = 2^5) {
  
  if (sum(abs(y)) == 0) return(x)
  
  g <- function(a) return(f(x + a*y))
  
  a.l <- 0
  g.l <- g(a.l)
  a.m <- 1
  g.m <- g(a.m)
  while ((g.m < g.l) & (a.m > tol)) {
    a.m <- a.m/2
    g.m <- g(a.m)
  }
  
  if ((a.m <= tol) & (g.m < g.l)) return(x)
  
  a.r <- 2*a.m
  g.r <- g(a.r)
  while ((g.m < g.r) & (a.r < a.max)) {
    a.m <- a.r
    g.m <- g(a.m)
    a.r <- 2*a.m
    g.r <- g(a.r)
  }
  
  if ((a.r >= a.max) & (g.m < g.r)) return(x + a.max*y)
  
  a <- gsection(g, a.l, a.r, a.m)
  return(x + a*y)
}