# Looping through partial sums

• Mathematica

## Summary:

Does Mathematica optimize the calculation of a series of partial sums automatically?
In this example,
Code:
DiscretePlot[    Sum[   f[x],   {x,1,n}  ],{n,1,20}]
will Mathematica automatically optimize the procedure -- i.e., will it run a single loop where it calculates the sum up to 20 only once, transferring the partial sums to the output as it goes along? Assume that there is no formula for the sum of f[x], so it has to actually add the terms up one by one.

Related MATLAB, Maple, Mathematica, LaTeX News on Phys.org
DrClaude
Mentor
In my experience, it is hard to know how Mathematica works behind the scenes, so optimization can be hard.

Looking at the book Programming with Mathematica by Paul Wellin, I have found that the most efficient way to make the sum is to first create the list of input, and then use Total instead of Sum:
Code:
In:= Timing[result = Table[Sum[f[x], {x, 1, n}], {n, 1000}];]
Out:= {0.72136, Null}

In:= Timing[x = Table[n, {n, 1000}];
result = Table[Total[f[Take[x, n]]], {n, 1000}];]
Out:= {0.009547, Null}

• • JD_PM and Swamp Thing