Mathematica Will Mathematica Optimize Looping for Partial Sums?

  • Thread starter Thread starter Swamp Thing
  • Start date Start date
  • Tags Tags
    Partial Sums
Swamp Thing
Insights Author
Messages
1,045
Reaction score
775
TL;DR
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.
 
Physics news on Phys.org
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

Similar threads

  • · Replies 4 ·
Replies
4
Views
3K
Replies
5
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 6 ·
Replies
6
Views
10K