# R中的梯度下降，用于非线性优化（nloptr程序包）

R提供了一个解决非线性问题的程序包：nloptr

``````＃加载包
library(nloptr)

＃定义要优化的功能
eval_f <- function(x){
return(
list(
"objective"=x[1]^2+x[2]^2,
2*x[2])
)
)
}

＃定义表示不等式约束“ <= 0”的函数
eval_g_ineq <- function(x){
return(
list(
"constraints"=x[1]+x[2]-100,
"jacobian"=c(1,
1)
)
)
}

＃定义起点
x_0 <- c(0,0)

＃nloptr文档文件建议的其他设置
＃这些设置，例如定义精确的优化算法
local_opts <- list( "algorithm" = "NLOPT_LD_MMA",
"xtol_rel"  = 1.0e-7 )

opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
"xtol_rel"  = 1.0e-7,
"maxeval"   = 1000,
"local_opts" = local_opts )

＃建模并解决问题
solution <- nloptr(x0=x_0,
eval_f=eval_f,
lb=NULL,
ub=NULL,
eval_g_ineq = eval_g_ineq,
eval_g_eq = NULL,
opts=opts)``````

``print(solution)``
``````##
## Call:
##
## nloptr(x0 = x_0, eval_f = eval_f, lb = NULL, ub = NULL, eval_g_ineq = eval_g_ineq,
##     eval_g_eq = NULL, opts = opts)
##
##
## Minimization using NLopt version 2.4.2
##
## NLopt solver status: 3 ( NLOPT_FTOL_REACHED: Optimization stopped because
## ftol_rel or ftol_abs (above) was reached. )
##
## Number of Iterations....: 102
## Termination conditions:  xtol_rel: 1e-07 maxeval: 1000
## Number of inequality constraints:  1
## Number of equality constraints:    0
## Optimal value of objective function:  1.09462903864043e-94
## Optimal value of controls: -7.398071e-48 -7.398071e-48``````