gpt4 book ai didi

r - 使用 R nloptr 包进行最小化 - 多重等式约束

转载 作者:行者123 更新时间:2023-12-03 15:52:12 24 4
gpt4 key购买 nike

是否可以在 nloptr 中指定多个等式约束? R中的函数?我试图运行的代码如下:

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 中指定多个等式约束函数或者我以错误的方式传递了它们。
我没有在包文档中找到任何具有多个等式约束的示例。

更新

好的,我解决了。情况是指定 constrgradeval_g_eq , 应该使用 rbind()而不是 c() .

最佳答案

我最近在另一篇关于不等式约束的帖子中回答了这个问题,但是您应该能够使用 c() 返回向量中的多个等式约束。
"multiple inequality constraints" - Minimization with R nloptr package

关于r - 使用 R nloptr 包进行最小化 - 多重等式约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com