Re: Re: Mathematica slows down

*To*: mathgroup at smc.vnet.net*Subject*: [mg53008] Re: [mg52987] Re: Mathematica slows down*From*: DrBob <drbob at bigfoot.com>*Date*: Sun, 19 Dec 2004 06:15:11 -0500 (EST)*References*: <200412180900.EAA02311@smc.vnet.net>*Reply-to*: drbob at bigfoot.com*Sender*: owner-wri-mathgroup at wolfram.com

Brilliant!! I didn't recognize the repeated differences. Next time, maybe. The eye-opener is that Prime is incredibly fast; I went into this thinking that was the time-waster, and it isn't. Not even close. Bobby On Sat, 18 Dec 2004 04:00:39 -0500 (EST), Bill Rowe <readnewsciv at earthlink.net> wrote: > On 12/17/04 at 5:20 AM, george at netvision.net.il (George Szpiro) > wrote: > > >> the following program runs ok for the first 6,000 iterations, then >> slows down considerably, and then seems to speed up again after >> 10,000. Does anyone know what is going on? > > >> NumP=15000; > >> For[k=1,k<NumP,k++, > >> Gap[1]=Prime[k+1]-Prime[k]; Gap[2]=Prime[k+2]-2Prime[k+1]+Prime[k]; >> Gap[3]=Prime[k+3]-3Prime[k+2]+3Prime[k+1]-Prime[k]; >> Gap[4]=Prime[k+4]-4Prime[k+3]+6Prime[k+2]-4Prime[k+1]+Prime[k]; > >> If[Mod[k,1000]==0, Print[ k]] > >> ] > > I don't know why you are seeing the slow down you report, but I do know this computation can be speeded up enormously > > First, changing your code slightly so as to retain each of the computed gaps and reducing NumP to make the overall execution time of your code smaller > > NumP = 5000; > gaps = {}; > Timing[ > For[k = 1, k < NumP, k++, > gaps = > Append[ > gaps, > {Prime[k+1]-Prime[k], > Prime[k+2]-2*Prime[k+1]+Prime[k], > Prime[k+3]-3*Prime[k+2]+3*Prime[k+1]-Prime[k], > Prime[k+4]-4*Prime[k+3]+6*Prime[k+2]-4*Prime[k+1]+Prime[k]}]]; ] > > {1.2999999999999972*Second, Null} > > Now for a different way to do the same computation > > Timing[newGaps = > Take[#1, NumP-1]&/@Rest[ > NestList[ > ListConvolve[{1, -1},#1]&,Prime/@Range[NumP+3],4]]; ] > > {0.020000000000003126*Second, Null} > > And finally, > > Transpose[newGaps] == gaps > > True > > Showing both methods do the same thing. > > The improved computation speed results from not computing Prime[k] more than needed and replacing the For loop with Mathematica's functional programming constructs. > -- > To reply via email subtract one hundred and four > > > > -- DrBob at bigfoot.com www.eclecticdreams.net

**References**:**Re: Mathematica slows down***From:*Bill Rowe <readnewsciv@earthlink.net>