Mathematica Will Mathematica Optimize Looping for Partial Sums?

  • Thread starter Thread starter Swamp Thing
  • Start date Start date
  • Tags Tags
    Partial Sums
AI Thread Summary
Mathematica does not automatically optimize looping for partial sums when using the Sum function, resulting in multiple calculations of the same terms. Instead, creating a list of inputs and using Total is significantly more efficient, as demonstrated by timing comparisons. The example shows that using Total with a precomputed list of values drastically reduces computation time compared to repeated calls to Sum. Additionally, the Accumulate function is suggested as an alternative for generating running totals. Overall, manual optimization techniques are necessary for improved performance in Mathematica.
Swamp Thing
Insights Author
Messages
1,028
Reaction score
763
TL;DR 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.
 
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
Views
3K
Replies
8
Views
2K
Replies
3
Views
3K
Replies
1
Views
4K
Replies
3
Views
3K
Replies
6
Views
10K
Back
Top