【发布时间】:2015-10-04 13:30:40
【问题描述】:
是否可以在 R 中的 nloptr 函数中指定多个等式约束?我尝试运行的代码如下:
eval_f <- function( x ) {
return( list( "objective" = x[3]^2+x[4]^2,
"gradient" = c( 0,
0,
2*x[3],
2*x[4] ) ) )
}
# constraint functions
# equalities
eval_g_eq <- function( x ) {
constr <- c( x[1] + x[2] + x[3] - 4,
x[1]^2 + x[2]^2 + x[4] - 15
)
grad <- c( c(1, 1, 1, 0),
c(2*x[1], 2*x[2], 0, 1)
)
return( list( "constraints"=constr, "jacobian"=grad ) )
}
# initial values
x0 <- c( 1, 5, 5, 1 )
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 )
res <- nloptr( x0=x0,
eval_f=eval_f,
eval_g_eq=eval_g_eq,
opts=opts)
print( res )
它产生的结果如下:
Current value of controls: -1.035323 3.093593 2.409501 0.2708714
但是这些值不具有等式约束,即
-1.035323 + 3.093593 + 2.409501 = 4.467771
(-1.035323)^2 + 3.093593^2 + 0.2708714 = 10.91308
我猜要么不可能在nloptr 函数中指定多个等式约束,要么我以错误的方式传递它们。
我在包文档中没有找到任何具有多个等式约束的示例。
更新
好的,我解决了。案例是在eval_g_eq 中指定constr 和grad,应该使用rbind() 而不是c()。
【问题讨论】:
-
你想要的质量限制是什么?第一个平方、第二个平方和第四个平方之和等于 15?
-
是的,这正是我想要的。
-
您好,请告诉我这是否可以用于需求优化的价格。我想使用 NLP。
标签: r constraints equality nonlinear-optimization nlopt