使用R优化功能

时间:2019-03-21 10:23:54

标签: r optimization

我有一个功能:

f(x1, x2) = (x2-x1)/(c-x1), 
where 0<x1,x2<1 and c = 0, 1

现在,我需要以f(x1,x2)保持在[-1,1]范围内的方式优化函数。我正在尝试使用以下R代码解决此问题。

require("stats")

# c=0
f <- function(x) { (x[2] - x[1]) / (0 - x[1]) }
initial_x <- c(0.1, 0.1)
x_optimal <- optim(initial_x, f, method="CG")
x_min <- x_optimal$par
x_min 
x_optimal$value

# c=1
f <- function(x) { (x[2] - x[1]) / (1 - x[1]) }
initial_x <- c(0.1, 0.1)
x_optimal <- optim(initial_x, f, method="CG")
x_min <- x_optimal$par
x_min 
x_optimal$value

但是它不起作用。谁能帮我解决这个问题?提前致谢。

1 个答案:

答案 0 :(得分:1)

这里是nloptr软件包的解决方案。我会c=1这个案子。

library(nloptr)

# c = 1
# objective function (to minimize)
f <- function(x) (x[2]-x[1]) / (1-x[1])

# constraints
# f(x) < 1  <=> x2-x1 < 1-x1 <=> x2 < 1
# f(x) > -1 <=> x2-x1 > x1 - 1 <=> 2*x1 - x2 - 1 < 0
# => constraint function
g <- function(x) 2*x[1] - x[2] - 1

# run optimization
opt <- nloptr(
  x0 = c(0.5, 0.5), 
  eval_f = f, 
  lb = c(0, 0),
  ub = c(1, 1), 
  eval_g_ineq = g, 
  opts = list(algorithm = "NLOPT_LN_COBYLA")
)

我们获得:

> # solution
> opt$solution
[1] 0.7569765 0.5139531
> # value of objective function
> opt$objective
[1] -1

现在是c=0

library(nloptr)

# c = 0
# objective function (to minimize)
f <- function(x) (x[1]-x[2]) / x[1]

# constraints
# f(x) < 1 <=> x1-x2 < x1 <=> x2 > 0
# f(x) > -1 <=> x1-x2 > -x1 <=> x2 - 2*x1 < 0
# => constraint function
g <- function(x) x[2] - 2*x[1] 

# run optimization
opt <- nloptr(
  x0 = c(0.5, 0.5), 
  eval_f = f, 
  lb = c(0, 0),
  ub = c(1, 1), 
  eval_g_ineq = g, 
  opts = list(algorithm = "NLOPT_LN_COBYLA")
)

我们得到:

> # solution
> opt$solution
[1] 0.5 1.0
> # value of objective function
> opt$objective
[1] -1