Nonlinear discrete optimization in R

前端 未结 4 1635
执念已碎
执念已碎 2021-01-20 19:17

I have a simple (indeed standard in economics) nonlinear constrained discrete maximisation problem to solve in R and am having trouble. I found solutions for pa

4条回答
  •  孤街浪徒
    2021-01-20 19:18

    I think this problem is very similar in nature to this question (Solve indeterminate equation system in R). The answer by Richie Cotton was the basis to this possible solution:

    df <- data.frame(product=c("ananas","banana","cookie"),
                     price=c(2.17,0.75,1.34),stringsAsFactors = F)
    
    FUN <- function(w, price=df$price){
      total <- sum(price * w) 
      errs <- c((total-20)^2, -(sqrt(w[1]) * sqrt(w[2]) * sqrt(w[3])))
      sum(errs)
    }
    
    init_w <- rep(10,3)
    res <- optim(init_w, FUN, lower=rep(0,3), method="L-BFGS-B")
    res
    res$par # 3.140093 9.085182 5.085095
    sum(res$par*df$price) # 20.44192
    

    Notice that the total cost (i.e. price) for the solution is $ 20.44. To solve this problem, we can weight the error terms to put more emphasis on the 1st term, which relates to the total cost:

    ### weighting of error terms
    FUN2 <- function(w, price=df$price){
      total <- sum(price * w) 
      errs <- c(100*(total-20)^2, -(sqrt(w[1]) * sqrt(w[2]) * sqrt(w[3]))) # 1st term weighted by 100
      sum(errs)
    }
    
    init_w <- rep(10,3)
    res <- optim(init_w, FUN2, lower=rep(0,3), method="L-BFGS-B")
    res
    res$par # 3.072868 8.890832 4.976212
    sum(res$par*df$price) # 20.00437
    

提交回复
热议问题