1

Here is my function that does a loop:

answer = function(a,n) {
  for (k in 0:n) {
    x =+ (a^k)/factorial(k)
    }
  return(x)
  }

answer(1,2) should return 2.5 as it is the calculated value of

1^0 / 0! + 1^1 / 1! + 1^2 / 2! = 1 + 1 + 0.5 = 2.5

But I get

answer(1,2)
#[1] 0.5

Looks like it fails to accumulate all three terms and just stores the newest value every time. += does not work so I used =+ but it is still not right. Thanks.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
colbyjackson
  • 175
  • 2
  • 10

1 Answers1

5
answer = function(a,n) {
  x <- 0  ## initialize the accumulator
  for (k in 0:n) {
    x <- x + (a^k)/factorial(k)  ## note how to accumulate value in R
    }
    return(x)
  }

answer(1, 2)
#[1] 2.5

There is "vectorized" solution:

answer = function(a,n) {
  x <- a ^ (0:n) / factorial(0:n)
  return(sum(x))
  }

In this case you don't need to initialize anything. R will allocate memory behind that <- and sum.

You are using Taylor expansion to approximate exp(a). See this Q & A on the theme. You may want to pay special attention to the "numerical convergence" issue mentioned in my answer.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • Do we always need to initialize the accumulator, x before for statement? – colbyjackson Sep 10 '18 at 23:48
  • In the case of the "nonvectorized" solution, you need to do that, as otherwise R would not know on the first iteration what the x in `<- x + ` would be and return an error that the object does not exist. – ira Sep 11 '18 at 06:34