roptimizationmaximization

Find a value that gives the local maximum of a function that takes two input variables


I asked a similar question earlier but my question wasn't clear. Here's another attempt.

Suppose you have the following function that takes two inputs, a and b.

inputs <- c(a, b)

y <- function(inputs) {
  a <- inputs[1]
  b <- inputs[2]
  output <- a/100 * (20 * b)^0.8 + (100 - a) / 100 * (10 * (100 - b))^0.8
  return(output)
}

For all possible values of a in the range [0, 100], I want to find the value of b that maximizes the output of the function above, with the restriction that b also has to be a value in the range [0, 100].

In other words, I want to plot b as a function of a, such that b maximizes the output value of the function above for the given value of a.

How would you write the code for this?


Solution

  • First of all, I would rewrite the function as a function of two parameters, by this order, b and a. This is because R base function optimize optimizes on its first argument. From the documentation:

    The function optimize searches the interval from lower to upper for a minimum or maximum of the function f with respect to its first argument.

    The default is to minimize, to maximize set the respective argument to TRUE.
    Then, in order to maximize for values of a in the interval [0, 100] run the optimization function for a sequence of a values. The result is stored in a list, coerced to data.frame and plotted.

    y <- function(b, a) {
      output <- a/100 * (20 * b)^0.8 + (100 - a) / 100 * (10 * (100 - b))^0.8
      output
    }
    
    a <- seq(0, 100, by = 0.1)
    max_list <- lapply(a, function(.a){
      optimize(y, interval = c(0, 100), .a, maximum = TRUE, tol = .Machine$double.eps^0.5)
    })
    
    max_data <- do.call(rbind.data.frame, max_list)
    row.names(max_data) <- NULL
    head(max_data)
    #       maximum objective
    #1 9.302363e-09  251.1886
    #2 9.302363e-09  250.9375
    #3 9.302363e-09  250.6863
    #4 9.302363e-09  250.4351
    #5 9.302363e-09  250.1839
    #6 9.302363e-09  249.9327
    
    
    plot(objective ~ maxima, max_data)
    

    enter image description here