Rudro88
Rudro88

Reputation: 231

Optimizing a function using R

I have a function:

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

Now I need to optimize the function in this way where f(x1, x2) will stay in the range [-1, 1]. I am trying to solve this using the following R code.

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

But it is not working. Could anyone help me to solve this? Thanks in advance.

Upvotes: 0

Views: 62

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84719

Here is a solution with the nloptr package. I treat the case 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")
)

We obtain:

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

Now the case 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")
)

We get:

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

Upvotes: 1

Related Questions