首页 > 解决方案 > R 代码:使用最陡下降求根

问题描述

我们的任务之一是编写一个固定步长的最陡下降函数来找到 Rosenbrock 函数的最小值 f(x,y)=100(yx^2)^2+(1-x)^2。我们已经知道最小值出现在 (1, 1) 处,因此需要让函数逼近它。

我觉得我的功能正在运行,但即使经过 100,000 次迭代,它找到的最小值也不正确 - 100,000 次迭代后的最终输出约为。(0.5348, 0.2185)。这个数字不会随着迭代的增加而改变。我确定我对这个函数做错了什么,但就是不知道在哪里。

fixed <- function(x = 4, y = 4){
  i <- 1
  si <- 0.1   ##fixed stepsize
  h <- function(x, y) {100*(y-x^2)^2+(1-x)^2} 
  dhx <- function(x, y) (-400*x*(y-x^2)-2+(2*x)) ##partial derivative for gradient
  dhy <- function(x, y) (200*(y-x^2))
  v <- c(x, y)    ## vector that contains the x and y value, which starts at (4,4)
  for (i in 0:100000){
    gradh <- c(-dhx(x,y), -dhy(x,y))  ##negative gradient to find minimum 
    di <- gradh/sqrt((dhx(x,y))^2+(dhy(x,y))^2) ##normalized direction 
    v <- v + (si*di)   ##calculating new direction
    x <- v[1]          ##breaking down the direction components to feed into the for loop
    y <- v[2]
    i <- i + 1
#    print(i)
#    print(gradh)
#    print(di)
#    print(v)
#    print(h(v[1], v[2]))
  }
  print(i)
  print(v)    ## v should be (1,1) after some iteration
}

标签: rnumerical-methods

解决方案


推荐阅读