richard外推法求梯度。一般h=10^-3。
下面给个例子,
f(x1,x2)=100(x2-x1^2)^2+(1-x1)^2,求x0=(1,0.5)的梯度。
如下为R代码
df <- function(x1,x2,...)
{
h= 0.001
f(x1,x2)
dfx1 <- (8*(f(x1+h,x2)-f(x1-h,x2))-f(x1+2*h,x2)+f(x1-2*h,x2))/(12*h)
dfx2 <- (8*(f(x1,x2+h)-f(x1,x2-h))-f(x1,x2+2*h)+f(x1,x2-2*h))/(12*h)
return(list(dfx1,dfx2))
}
f <- function(x1,x2)
{
value <- 100*(x2-x1^2)^2+(1-x1)^2
return(value)
}
执行结果为:
df(1,0.5)
df(1,0.5)
[[1]]
[1] 200
[[2]]
[1] -100