r - 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
}
解决方案
推荐阅读
- android - loadUrl 正在使用不适用于本地 html 页面的链接(在片段中不是活动)
- php - 为什么删除 ajax 加载更多插件后,我的 WordPress 电子商务网站中的导航样式不正确?
- ember.js - 如何在ember js中动态更改app.scss值
- android - 使用命令行运行android模拟器
- javascript - 在单个链中更新、进入和退出选择
- javascript - javascript隐藏测试/图片
- c++ - 如何为 QUrl 重定向是否返回布尔值?
- node.js - 当我使用 window.open() 时,我无法在新窗口中打开文件
- php - 如何使用 array_flip 在 PHP 中翻转多维数组
- python - 如何在将标题/列名称保持在顶部的同时将行打印到命令行?