Maximize a function with constraints

353 Views Asked by At

I have the following function which i maximize using optim().

Budget = 2000 

X = 4
Y = 5


min_values = c(0.3,0)
start_values = c(0.3,0.5)
max_values = c(1,1)



sample_function <- function(z,Spend){
  Output = (z[1]*X*Spend) + (z[2]*Y*Spend) 
  return(Output)
}


MaxFunction <- optim(par=start_values ,fn= sample_function, method = "L-BFGS-B", lower = min_values , upper= max_values  ,control=list(maxit=100000 ,fnscale=-1), Spend= Budget)

However i would like to add some constraints when maximizing such as:

 z[1] => 1/3

and

 z[1] + z[2] = 1 

Any help will much be appreciated since this is linked to a more complicated problem that i'm tackling. Or if there's a different method for solving the problem without using otpim() please let me know.

1

There are 1 best solutions below

3
ThomasIsCoding On

optim is not a good option for constrained optimization, but it is still possible for your case as long as you formulate your objective function sample_function in a different way.

Below is an example

min_values = 1/3
start_values = 0.5
max_values = 1

sample_function <- function(z,Spend){
    z*X*Spend + (1-z)*Y*Spend
}

MaxFunction <- optim(par=start_values ,
                     fn= sample_function, 
                     method = "L-BFGS-B", 
                     lower = min_values , 
                     upper= max_values,
                     control=list(maxit=100000 ,fnscale=-1), 
                     Spend= Budget)

If you want to see the distribution of elements of z and 1-z, you can use

z1 <- MaxFunction$par
z2 <- 1- z1
Zopt <- c(z1,z2)

such that

> Zopt
[1] 0.3333333 0.6666667