R优化最小值

时间:2013-06-12 23:24:00

标签: r

我有一个功能,我想找到最小值

start.capital =  2000000
target.capital = 49594660
monthly.inflation = 0.002
monthly.deposits = 50000
n.obs = 240

fn<-function(monthly.mean.return,
         start.capital,
         monthly.inflation,
         monthly.deposits,
         n.obs,
         target.capital){

  #monthly.mean.return = annual.mean.return / 12
  #monthly.inflation = annual.inflation / 12

  req = matrix(start.capital, n.obs+1, 1)
  for (a in 1:n.obs) {
    req[a + 1, ] = req[a, ] * (1 + monthly.mean.return - monthly.inflation) + monthly.deposits
  }
  ending.value=req[nrow(req),]
  value<-target.capital - ending.value
  return(value)
}

我想尽量减少“monthly.mean.return”。正确的答案是0.01,但我的数字很大......

我在尝试:

optimize(f=fn,
     monthly.mean.return,
     start.capital,
     monthly.inflation,
     monthly.deposits,
     n.obs,
     target.capital,
     lower=0)

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

措辞很重要。您并未尝试最小化monthly.mean.return,而是尝试将fnmonthly.mean.return相比最小化。

首先,您的目标是到达target.capital,您的fn函数不应返回target.capital - ending.value,而应返回绝对错误abs(target.capital - ending.value)。我希望您能看到原因(optimize正在尝试使fn的输出值尽可能小。)

然后,您显然没有正确调用optimize函数。以下是您需要如何继续传递这些预先指定的参数:

optimize(f=fn, 
         start.capital = start.capital,
         monthly.inflation = monthly.inflation,
         monthly.deposits = monthly.deposits,
         n.obs = n.obs,
         target.capital = target.capital,
         lower = 0,
         upper = 1)

$minimum
[1] 0.01001939

$objective
[1] 170750.9