Jasmin
Jasmin

Reputation: 49

Using optim() - two equations two unknowns R

I am trying to use optim() to solve & maxim. the following equation system:

model <- function(z) {
    q1 <- z[1]
    q2 <- z[2]
    return ((10-2*(q1+q2))*q1-k1*q1)
    return ((10-2*(q2+q1))*q2-k2*q2)
}

The paramters/variables are defined as follows:

A <- rep(0,2)
lowerb <- rep(0,2)
upperb <- rep(6,2) 
k1 <- 3
k2 <- 2

and the rest as follows:

optim(A, model, gr=NULL, method="L-BFGS-B", lower = lowerb, upper = upperb, control = list(fnscale = -1, trace = 1))$par

I do not receive an error, however, the maxima are supposed to be at q1=1 and q2=1,5 and not at 1,75 and 0, as R is stating at the moment. Since I need to apply this to a much more complex equation system, I did use an easy equation to start with, which one can easily calculate manually.

Help is appreciated! Thanks a lot!

Upvotes: 0

Views: 951

Answers (1)

masa
masa

Reputation: 11

k1 <- 3
k2 <- 2
q2 <- 0
q2 <- 0 
for (i in 1:20) {
  #For 1
  objective1 <- function(q) ((10-2*(q+q2))*q-k1*q)
  result1 <- optimize(objective1, c(0,10), maximum = TRUE)
  q1 <- result1$maximum 
  #For 2
  objective2 <- function(q) ((10-2*(q1+q))*q-k2*q)
  result2 <- optimize(objective2, c(0,10), maximum = TRUE)
  q2 <- result2$maximum 
  }
q1
q2

Upvotes: 1

Related Questions