Message Boards Message Boards

3
|
168 Views
|
3 Replies
|
6 Total Likes
View groups...
Share
Share this post:

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

Posted 4 days ago

https://unsplash.com/photos/pen-om-paper-AT77Q0Njnt0?utm<em>content=creditShareLink&utmmedium=referral&utm_source=unsplash

Attachments:
POSTED BY: Theo V
3 Replies

Thanks for sharing!

My answer in the discussion, https://community.wolfram.com/groups/-/m/t/3195262, 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
POSTED BY: Michael Rogers

If we consider readability I would prefer:

({x,y} |-> x^2 + y^2)[3, 2]

versus:

(#1^2 + #2^2)&[3, 2]
POSTED BY: Robert Nowak
Posted 4 days ago

Thank you very much for the reply! That's a really interesting consideration, it's quite astounding the difference in time recorded: I also saw ~5s difference which is brilliant.

In regard to the Total[Table[...]] and Sum[...], I really like that way of looking at it. It's another nice example too, at least in my eyes, of how the two both have their purposes, depending on whether anyone else will be looking at the code.

That is odd how my timing varies so much compared to yours though, I'll have to try and check it out; I'm not sure whether it could be bigInt like you say or maybe just a difference in handling overall. Much appreciated, best wishes!

POSTED BY: Theo V
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract