【问题标题】:Optimizing a function using R使用 R 优化函数
【发布时间】:2019-03-23 16:11:52
【问题描述】:

我有一个函数:

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

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

【问题讨论】:

    标签: r optimization


    【解决方案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
    

    【讨论】:

    • 谢谢。但是当我尝试 c=0 时,它在目标函数中显示 -Inf。
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多