Looping through partial sums

  • Mathematica
  • Thread starter Swamp Thing
  • Start date
  • #1

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.
 

Answers and Replies

  • #2
DrClaude
Mentor
7,505
3,786
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[1]:= Timing[result = Table[Sum[f[x], {x, 1, n}], {n, 1000}];]
Out[1]:= {0.72136, Null}

In[2]:= Timing[x = Table[n, {n, 1000}];
 result = Table[Total[f[Take[x, n]]], {n, 1000}];]
Out[2]:= {0.009547, Null}
 
  • Informative
  • Like
Likes JD_PM and Swamp Thing

Related Threads on Looping through partial sums

  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
1
Views
791
Replies
4
Views
771
Replies
25
Views
8K
  • Last Post
Replies
5
Views
2K
  • Last Post
Replies
2
Views
605
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
3
Views
2K
Top