0

I'm currently studying basic growth functions. Since R is not really good at dealing with symbollic equations, I'm writing both the growth function, as well as it´s derivative to later apply the Newton-Raphson method. The code is looking like this:

invested <- c(10000, 20000, 15000, 30000)
rates <- c(5e-3, 6e-3, 7e-3, 8e-3)

amount <- 0

prediction <- function(t){
  for(i in invested){
    for(j in rates){
      parcel <- i * exp(j * t)
    } 
    amount <- amount + parcel
  }
  print(amount)
}

dt <- 0
dpred <- function(t){
  for(i in invested){
    for(j in rates){
      parcial <- (j*i) * exp(j * t)
    } 
    dt <- dt + parcial
  }
  print(dt)
}

The problem is it spits out prediction(1) is 85,59 too much for the actual value I found testing with the following code:

(10000*exp(5e-3))+(20000*exp(6e-3))+(15000*exp(7e-3))+(30000*exp(8e-3))

The derivative dpred(1) is also off by a quite big margin, according to my previous calculations. Any ideas on why is the error so big and how to get rid of it?

  • 1
    In both functions, you change `parcel` for each rate, but the assignment overwrites `parcel` every time, only the final rate matters. Maybe you need the `amount <- amount + parcel` (or `dt` updating) *inside* the inner loop? Or maybe you want a vector of `parcel`s? – Gregor Thomas Dec 02 '19 at 02:07
  • 1
    Also, don't `print` inside your functions -- that will get annoying. `return()` the result at the end. If you want to print it to console, use `message()` so that it can be switched off easily (e.g., with `suppressMessages()`) – Gregor Thomas Dec 02 '19 at 02:08
  • 1
    I'm also confused by your `for` loops vs your testing code. Your for loops, nested, will have an iteration for *every* combination of investment and rate. However your test code only shows 1st investment with 1st rate, 2nd investment with 2nd rate, etc. If your test code is what you want, just do `sum(invested * exp(rate))`, completely vectorized, no loop needed. – Gregor Thomas Dec 02 '19 at 02:12
  • IT WORKED! Thanks a lot, it took me a while to understand what you were saying, but it not only worked, but the code is way more simple now. – crawlingnotballing Dec 02 '19 at 03:01

1 Answers1

0

Edit

invested <- c(10000, 20000, 15000, 30000)
rates <- c(5e-3, 6e-3, 7e-3, 8e-3)

prediction <- function(t){
  amount <- sum(invested * exp(rates*t))
  return(amount)
}
Community
  • 1
  • 1
Zhiqiang Wang
  • 6,206
  • 2
  • 13
  • 27
  • Yes, you're correct, it was only picking the last 30000. And about the ```prediction``` , the ```test``` code was correct, I only needed the first ```invested``` with the first ```rate```, the second ```invested``` with the second ```rate``` and so on. – crawlingnotballing Dec 02 '19 at 03:43
  • Great! In that case no `for` loop is needed. Obvious, you have already worked out the solution. I have edited my answer. – Zhiqiang Wang Dec 02 '19 at 04:31