更新时间:2023-11-03 23:34:10
constrOptim()
使用线性不等式约束并通过ui %*定义可行域% 参数 - ci >= 0
.如果约束是 3 * d1 + d2 ,
ui
是 c(-3, -1)
和 ci
是 -280
.
constrOptim()
uses linear inequality constraints and defines the feasible region by ui %*% param - ci >= 0
. If the constraint is 3 * d1 + d2 <= 280
, ui
is c(-3, -1)
and ci
is -280
.
Fd <- function(betas) {
b1 = betas[1]
b2 = betas[2]
(224 * b1 + 84 * b2 + b1 * b2 - 2 * b1^2 - b2^2)
}
theta = c(59.999,100) # because of needing " ui %*% inital_par - ci > 0 "
ui = c(-3, -1)
ci = -280 # those ui & ci mean " -3*par[1] + -1*par[2] + 280 >= 0 "
constrOptim(theta, Fd, NULL, ui = ui, ci = ci, control=list(fnscale=-1))
# $par
# [1] 69.00002 72.99993
如果你想要的不是不等式而是等式约束,***使用 Rsolnp
或 alabama
包.他们可以使用不等式和/或等式约束(参见用于等式和不等式约束的约束优化库).
If you want not inequality but equality constraints, it would be better to use Rsolnp
or alabama
package. They can use inequality and/or equality constraints (see Constrained Optimization library for equality and inequality constraints).
library(Rsolnp); library(alabama);
Fd2 <- function(betas) { # -1 * Fd
b1 = betas[1]
b2 = betas[2]
-1 * (224 * b1 + 84 * b2 + b1 * b2 - 2 * b1^2 - b2^2)
}
eqFd <- function(betas) { # the equality constraint
b1 = betas[1]
b2 = betas[2]
(3 * b1 + b2 -280)
}
solnp(pars = c(60, 100), fun = Fd2, eqfun = eqFd, eqB = 0)
auglag(par = c(60, 100), fn = Fd2, heq = eqFd)