Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive cumulative function

Tags:

r

I need to write a cumulative summation function in R but I've been hitting a brick wall. The function has the following structure:

a*x1
a*x2 + a^2*x1
a*x3 + a^2*x2 + a^3*x1
a*x4 + a^2*x3 + a^3*x2 + a^4*x1

And so on. cumsum doesn't seem to work for this type of function. Is there any way this could be implemented in R?

like image 236
user1536464 Avatar asked Jul 19 '12 01:07

user1536464


People also ask

What is a recursive function in CPP?

Recursion is a method in C++ which calls itself directly or indirectly until a suitable condition is met. In this method, we repeatedly call the function within the same function, and it has a base case and a recursive condition.

What is a recursive function example?

The classic example of recursive programming involves computing factorials. The factorial of a number is computed as that number times all of the numbers below it up to and including 1. For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

What is recursion in programming?

Recursion means “solving a problem using the solution of smaller subproblems (smaller version of the same problem)” or “defining a problem in terms of itself”. This is a widely used idea in data structures and algorithms to solve complex problems by breaking them down into simpler ones.


1 Answers

Since your recursion is

u[n+1] = a * ( x[n+1] + u[n] )

i.e.,

u[n+1]/a = x[n+1] + a * u[n]/a,

you can use filter:

x <- 1:5
a <- 2
a*filter(1:5, a, method="recursive")

# Compare with the expected values
a*x[1]
a*x[2] + a^2*x[1]
a*x[3] + a^2*x[2] + a^3*x[1]
a*x[4] + a^2*x[3] + a^3*x[2] + a^4*x[1]
like image 153
Vincent Zoonekynd Avatar answered Sep 16 '22 23:09

Vincent Zoonekynd