[英]Passing arguments to nloptr in r
I'm optimising a simple function in r using 'nloptr' and I'm having difficulty passing arguments in to the objective function. 我正在使用'nloptr'优化r中的一个简单函数,并且很难将参数传递给目标函数。 Here is the code I'm using:
这是我正在使用的代码:
require("nloptr")
Correl <- matrix(c(1,-.3,-.3,1), nrow=2, ncol=2)
Wghts <- c(.01,.99)
floor <- .035
expret <- c(.05,.02)
pf.return <- function(r, x, threshold=0){
return(r * x - threshold)
}
pf.vol <- function(x, C){
return(sqrt(x %*% C %*% x))
}
res <- nloptr(x0=Wghts,eval_f = pf.vol,eval_g_ineq=pf.return,opts=list(algorithm="NLOPT_GN_ISRES"), x=Wghts,C=Correl)
(I know I'm missing parameters here but I'm trying to highlight a behaviour I don't understand) Running this gives the following error: (我知道我在这里缺少参数,但是我想突出显示一个我不理解的行为)运行此命令会产生以下错误:
Error in .checkfunargs(eval_f, arglist, "eval_f") : x' passed to (...) in 'nloptr' but this is not required in the eval_f function.
Just to see what happens I can try running it without the x argument: 只是为了看看会发生什么,我可以尝试在没有x参数的情况下运行它:
res <- nloptr(x0=Wghts,eval_f = pf.vol,eval_g_ineq=pf.return,opts=list(algorithm="NLOPT_GN_ISRES"), C=Correl)
which gives the error: 给出错误:
Error in .checkfunargs(eval_g_ineq, arglist, "eval_g_ineq") : eval_g_ineq requires argument 'x' but this has not been passed to the 'nloptr' function.
So including x
throws an error that it is unnecessary and omitting it throws an (at least understandable) error that it has been omitted. 因此,包含
x
会引发不必要的错误,而忽略x
则会引发已被忽略的错误(至少是可以理解的)。
Ok for posterity: 后代还可以:
I rewrote the functions so that they had the same set of arguments, in the same order. 我重写了函数,以便它们具有相同的参数集,并且顺序相同。
I also omitted the x=Wghts
bit as this is the parameter I'm trying to search over. 我也省略了
x=Wghts
位,因为这是我要搜索的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.