Re: four approaches to do a simple sum

• To: mathgroup at smc.vnet.net
• Subject: [mg57244] Re: four approaches to do a simple sum
• Date: Sat, 21 May 2005 02:41:19 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```On 5/20/05 at 4:43 AM, fangh73 at xmu.edu.cn (Hui Fang) wrote:

>Here I have a long list, length of 1 million, and I used 4 ways to
>get the sum of all elements.

>In[1] = longlist=Table[Random[], {1000000}];

>Method 1:
>In[2] = Timing[sum=0; For[i=1,i<=Length[longlist],sum+=longlist[[i]]]; sum]
>Out[2] = {6.219 Second, 500358}

>Method 2:
>In[3] = Sum[longlist[[i]],{i,1,1000000}]
>Out[3] = {1.718 Second, 500358}

>Method 3:
>In[4] = Timing[Plus@@longlist]
>Out[4] = {0.407 Second, 500358}

>Method 4:
>In[5] = Fold[Plus,0,longlist]
>Out[5] = {0.156 Second, 500358}

>The computing time gets shorter and shorter from top to bottom.
>It's easy to understand why the first two methods are slow because
>they involved an extra variable i for loop control and basically
>violates the principle for list manipulation "Never take a list
>apart". What I don't understand is why method 4 is faster than
>method 3. Any explanation?Or do you have an even faster method?

Total provides a faster method to sum a list. For example,

In[1]:= \$Version
Out[1]= "5.1 for Mac OS X (January 27, 2005)"

In[2]:=longlist = Table[Random[], {1000000}];

In[3]:=Timing[Fold[Plus, 0, longlist]]
Out[3]={0.540862*Second, 499577.6754541984}

In[4]:=Timing[Total[longlist]]
Out[4]={0.022061*Second, 499577.6754541984}
--
To reply via email subtract one hundred and four

```

• Prev by Date: Re: runs test for evaluation of model fit
• Next by Date: Re: Printing from Mathematica 5.1
• Previous by thread: Re: four approaches to do a simple sum