【问题标题】:How to find the max value of a concave function in R如何在R中找到凹函数的最大值
【发布时间】:2021-07-21 21:03:42
【问题描述】:

谁能帮我重写代码不使用for循环?目标是找到最大化 calcProfit的支出价值。

在本例中,“calcVolume”和“calcProfit”是虚拟函数。在我的真实项目中:

  • 它们很复杂很复杂
  • 'calcProfit' 将是凹形的
  • 运行此循环将花费超过 1 分钟(因此对用户来说是不可取的)
    
set.seed(123)
spend = 150000

unit.x    <- spend/10 # x axis (unit)
max.x     <- spend*2  # x axis (max)

calcVolume <- function(spend) {
  runif(1,0,1)*spend
}

calcProfit <- function(vol) {
  runif(1,0,1)*vol
}
out <- as.data.frame(matrix(data = NA, nrow = 21, ncol = 2))

cnt <- 1

for (step.x in seq(0, max.x, by = unit.x)) {
  
  out[cnt, 1] <- step.x
  out[cnt, 2] <- calcVolume(step.x) 
  out[cnt, 3] <- calcProfit(out[cnt, 2])
  cnt   <- cnt + 1
}


【问题讨论】:

  • 您在寻找help("optimize") 还是help("optim")
  • 不完全。我进行了编辑以澄清我的问题。是的,我正在尝试优化 calcProfit,但这取决于 calcVolume。不确定我们是否可以使用“优化”来做到这一点。

标签: r for-loop optimization


【解决方案1】:

如果你有封闭形式涉及的功能,那么可以用optimize优化复合。

在下面的代码中我定义了一个辅助函数f

calcVolume <- function(x) {
  sin(x)
}
calcProfit <- function(x) {
  (x - 1)*(x - 2)*(x - 3)
}
f <- function(x){
  calcProfit(calcVolume(x))
}

M <- optimize(f, c(0, 3), maximum = TRUE)
M
#$maximum
#[1] 1.570796
#
#$objective
#[1] -7.327472e-15

curve(f, 0, 3)
points(M$maximum, M$objective, col = "red", pch = 16)

【讨论】:

    【解决方案2】:

    忽略生成随机数的顺序,可以尝试这样避免循环。

    V1 <- seq(0, max.x, by = unit.x)
    V2 <- calcVolume(V1)
    V3 <- calcProfit(V2)
    out2 <- data.frame(V1,V2,V3)
    

    您可以使用which.max 找到最大化 calcProfit 的支出价值

    out[which.max(out$V3),]$V1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多