Will Mathematica Optimize Looping for Partial Sums?

  • Context: Mathematica 
  • Thread starter Thread starter Swamp Thing
  • Start date Start date
  • Tags Tags
    Partial Sums
Click For Summary
SUMMARY

Mathematica does not automatically optimize looping for partial sums in the example provided. Instead, the most efficient method involves creating a list of inputs and using the Total function, which significantly reduces computation time from 0.72136 seconds to 0.009547 seconds. Additionally, the Accumulate function can be utilized to generate running totals or partial sums effectively. This insight is derived from the book "Programming with Mathematica" by Paul Wellin.

PREREQUISITES
  • Familiarity with Mathematica syntax and functions
  • Understanding of the Total function in Mathematica
  • Knowledge of the Accumulate function for generating partial sums
  • Basic concepts of timing and performance measurement in programming
NEXT STEPS
  • Explore the use of the Total function in Mathematica for performance optimization
  • Learn about the Accumulate function and its applications in Mathematica
  • Investigate timing functions in Mathematica to measure performance
  • Read "Programming with Mathematica" by Paul Wellin for advanced optimization techniques
USEFUL FOR

Mathematica users, data analysts, and programmers looking to optimize performance in mathematical computations and loop handling.

Swamp Thing
Insights Author
Messages
1,048
Reaction score
799
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   Reactions: 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
4K
  • · 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