title: R Optimization given objective function
body: <pre><code>obj1&lt;-function(monthly.savings,
                 success,
                 start.capital,
                 target.savings,
                 monthly.mean.return,
                 monthly.ret.std.dev,
                 monthly.inflation,
                 monthly.inf.std.dev,
                 n.obs,
                 n.sim=1000){
  
    req = matrix(start.capital, n.obs+1, n.sim) #matrix for storing target weight
  
    monthly.invest.returns = matrix(0, n.obs, n.sim)
    monthly.inflation.returns = matrix(0, n.obs, n.sim)
  
    monthly.invest.returns[] = rnorm(n.obs * n.sim, mean = monthly.mean.return, sd = monthly.ret.std.dev)
    monthly.inflation.returns[] = rnorm(n.obs * n.sim, mean = monthly.inflation, sd = monthly.inf.std.dev)
  
    #for loop to be 
    for (a in 1:n.obs){
      req[a + 1, ] = req[a, ] * (1 + monthly.invest.returns[a,] - monthly.inflation.returns[a,]) + monthly.savings
    }
  
    ending.values=req[nrow(req),]
    suc&lt;-sum(ending.values&gt;target.savings)/n.sim
    value&lt;-success-suc
  
    return(abs(value))
  }
  </code></pre>
  
  <p>I have the above objective function that I want to minimize for. It tries to solve for the monthly savings required for a given probability of success. Given the following input assumptions</p>
  
  <pre><code>success&lt;-0.9
  start.capital&lt;-1000000
  target.savings&lt;-1749665
  monthly.savings=10000
  monthly.mean.return&lt;-(5/100)/12
  monthly.ret.std.dev&lt;-(3/100)/sqrt(12)
  monthly.inflation&lt;-(5/100)/12
  monthly.inf.std.dev&lt;-(1.5/100)/sqrt(12)
  monthly.withdrawals&lt;-10000
  n.obs&lt;-10*12  #years * 12 months in a year
  n.sim=1000
  </code></pre>
  
  <p>I used the following notation:</p>
  
  <pre><code>optimize(f=obj1,
          success=success,
          start.capital=start.capital,
          target.savings=target.savings,
          monthly.mean.return=monthly.mean.return,
          monthly.ret.std.dev=monthly.ret.std.dev,
          monthly.inflation=monthly.inflation,
          monthly.inf.std.dev=monthly.inf.std.dev,
          n.obs = n.obs,
          n.sim = n.sim,
          lower = 0,
          upper = 10000,
          tol = 0.000000001,maximum=F)
  </code></pre>
  
  <p>I get 7875.03</p>
  
  <p>Since I am sampling from a normal distribution, the output will be different each time but they should be around the same give or take a few % points. The problem I am having is that I can't specify a upper limit arbitrarily. The above example's upper limit (10000) is cherry picked after numerous trials. If say I put in a upper limit of 100000 (unreasonable I know) it will return that number as oppose to finding the global minimum saving. Any ideas where I am structuring my objective function incorrectly? </p>
  
  <p>thanks,</p>