       Re: four approaches to do a simple sum

• To: mathgroup at smc.vnet.net
• Subject: [mg57213] Re: [mg57171] four approaches to do a simple sum
• From: "Caffa Vittorio Dr." <Caffa at iabg.de>
• Date: Sat, 21 May 2005 02:39:26 -0400 (EDT)
• Sender: owner-wri-mathgroup at wolfram.com

```
By the way:

Timing[Fold[Plus, 0, longlist]]
{0.22 Second, 499831.}

Timing[Total[longlist]]
{0.01 Second, 499831.}

Cheers, Vittorio

>-----Original Message-----
>From: Hui Fang [mailto:fangh73 at xmu.edu.cn]
To: mathgroup at smc.vnet.net
>Sent: Friday, May 20, 2005 10:43 AM
>Subject: [mg57213] [mg57171] four approaches to do a simple sum
>
>Here I have a long list, length of 1 million, and I used 4 ways to get
>the sum of all elements.
>
>In = longlist=Table[Random[], {1000000}];
>
>Method 1:
>In = Timing[sum=0; For[i=1,i<=Length[longlist],sum+=longlist[[i]]];
sum]
>Out = {6.219 Second, 500358}
>
>Method 2:
>In = Sum[longlist[[i]],{i,1,1000000}]
>Out = {1.718 Second, 500358}
>
>Method 3:
>In = Timing[Plus@@longlist]
>Out = {0.407 Second, 500358}
>
>Method 4:
>In = Fold[Plus,0,longlist]
>Out = {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?
>Thanks a lot!
>
>Hui Fang

```

• Prev by Date: Re: NonLinearRegress and constraint parameters
• Next by Date: Re: Mathematica 5.1 and Oracle 10g
• Previous by thread: Re: four approaches to do a simple sum
• Next by thread: Re: four approaches to do a simple sum