# How to iteratively integrate a function and sum the result of each iteration

I want to repeatedly integrated a function and add the result of each iteration. Suppose I start a with a function $f(x) = x$ , I want to integrated it, it will be $x^2/2$, and again integrating, it will be $x^3/6$, and at the end I want to get the result $x^2/2+x^3/6$.

-
Welcome to mathematica.SE. This site is for Mathematica programming related questions. If you have some code, please show us what you have tried so far. – Artes Sep 13 '13 at 7:11

Try

NestList[Integrate[#, x] &, x, 2] // Rest // Accumulate


to get the list of successive iterations or

NestList[Integrate[#, x] &, x, 2] // Rest // Total


to obtain only the last element.

-
Remarkable that for a big number of iterations it is almost as fast as exact Sum[x^n/n!, {n, 2, m}]! – ybeltukov Sep 13 '13 at 14:08

Here is another way using Reap and Sow with Nest instead of NestList, just to spice things up. Performance is identical on my machine.

f[fun_, n_Integer?Positive] := Total @@ Reap[Nest[Sow[Integrate[#, x]] &, fun, n]][[2]]


Which you can use for any nonnegative n, where fun is the function you which to iteratively integrate, like this:

f[x, 2]

x^2/2 + x^3/6

f[Log[x], 5]

 -x - (3 x^2)/4 - (11 x^3)/36 - (25 x^4)/288 - (137 x^5)/7200 +   x Log[x] + 1/2
x^2 Log[x] + 1/6 x^3 Log[x] + 1/24 x^4 Log[x] +   1/120 x^5 Log[x]

-
Total@Rest@NestList[Integrate[#, x] &, x, 2]

-