Bertrand
Bertrand

Reputation: 87

R: Recursive sum of functions of x

I would like to program a sum of k functions of x depending upon a index i=1,...k, and also depending on the a point x0 (it looks a bit like a Taylor formula). However, the following code produces the error message:

Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?

I would appreciate if somebody could help to improve on it:

cum_f <- function(x, x0, k){
  i <- 1
  p <- function(x,x0) x0^2
  while(i <= k){
    p = function(x,x0){ p(x,x0) + (x - x0)**i }
    i = i + 1
  }
  return(p(x,x0))
}
cum_f(x,1,5)
cum_f(10,1,5) 

Upvotes: 1

Views: 1569

Answers (1)

CPak
CPak

Reputation: 13581

Do you need recursion? Is this what you're looking to do?

cum_f <- function(x, x0, k){
              i <- 1
              p <- x0**2
              while(i <= k){
                   p <- p + (x - x0)**i
                   i = i + 1
              }
              return(p)
         }

 cum_f(10,1,5) 

 # 66430

Alternative

You can get the same result with this function

cum_f <- function(x, x0, k){
             val <- Reduce("+", c(x0**2, (x-x0)**(1:k)), accumulate=TRUE)
             return(tail(val,1))
         }

Or even simpler (thanks Roland)

cum_f <- function(x, x0, k){
             val <- x0^2 + sum((x-x0)^(1:k))
             return(val)
         }

cum_f(10,1,5) 
# 66430

Upvotes: 3

Related Questions