15 Functions for optimization and readability in the Wolfram Language, for beginners

Thanks for sharing!

My answer in the discussion, Sum and Product a feature request , discusses some differences between Total[] and Sum[], as well as a few other ways to add up a list of numbers. The principal difference I would emphasize is that Sum[] is a symbolic summation tool. Its symbolic analysis of the summand slows it down compared to a brute-force adding up of the number (via Table[]). On machine reals and integers, I think Total[] beats Sum[], unless there’s a symbolic formula; see example at end, although it doesn’t use machine numbers.

Interestingly, your Sum[..] and Total[Table[..]] examples take the same time on my Macbook Pro M1 Max, about 5.7 sec. It’s interesting that one is ~3 sec. slower and the other ~3 sec. faster than your computer. Maybe something to do with the bigInt library?

The fastest result for Sum[i^20, {i, 1000000}] can be obtained from the following (about 0.0004 sec. for me, much, much faster than 5.7 sec.):

Sum[i^k, {i, n}] /. {k -> 20, n -> 1000000} // 
   N[#, Ceiling@N[Log10@#, {$MaxPrecision, 1}]] & // 
  Round //
 AbsoluteTiming

It’s so fast that single calls to AbsoluteTiming[] are unreliable. FYI, here’s the timing code I used:

Table[
   ClearSystemCache[]; (* make Sum[] and N[] start from scratch *)
   Sum[i^k, {i, n}] /. {k -> 20, n -> 1000000} // 
       N[#, Ceiling@N[Log10@#, {$MaxPrecision, 1}]] & // Round // 
     AbsoluteTiming // First,
   1000]/1000 // Total
2 Likes