MathGroup Archive 2003

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: nth differences

  • To: mathgroup at smc.vnet.net
  • Subject: [mg39878] Re: [mg39852] nth differences
  • From: BobHanlon at aol.com
  • Date: Sun, 9 Mar 2003 05:30:30 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

In a message dated 3/8/03 10:44:12 AM, writes:

>
> In a message dated 3/8/03 3:35:44 AM, _NOzturnerSPAM_ at cyberonic.com writes:
>
>
> Say I have a list of k integers and I want to produce a list containing the
> first differences?  For example, given {1, 2, 5, 7, 8, 9} the first
> differences are {1, 3, 2, 1, 1}, and the second differences are {2, -1, -1,
> 0}, the third are {-3, 0, 1}, etc
>
> v = {1, 2, 5, 7, 8, 9};
>
>
> Rest[v-RotateRight[v]]
>
>
> {1,3,2,1,1}
>
>
> nthDifference[v_List, n_Integer] :=
> 
>      Nest[Rest[#-RotateRight[#]]&,v,n] /;
> 
>        0   <= n <= Length[v];
>
>
>
> nthDifferenceList[v_List, n_:Length[v]] :=
> 
>      NestList[Rest[#-RotateRight[#]]&,v,n] /;
> 
>        0 <= n <= Length[v] && IntegerQ[n];
>
> nthDifference[v,3]
>
>
> {-3,0,1}
>
>
> nthDifferenceList[v,3]
>
>
> {{1,2,5,7,8,9},{1,3,2,1,1},{2,-1,-1,0},{-3,0,1}}
>
>
> nthDifferenceList[v]
>
>
> {{1,2,5,7,8,9},{1,3,2,1,1},{2,-1,-1,0},{-3,0,1},{3,1},{-2},{}}
>
>
> Bob Hanlon
>
>

This shows a slightly faster method using listCorrelate

nthDifference1[v_List, n_Integer] :=

     Nest[Rest[#-RotateRight[#]]&,v,n] /;

       0   <= n <= Length[v];



nthDifferenceList1[v_List, n_:Length[v]] :=

     NestList[Rest[#-RotateRight[#]]&,v,n] /;

       0 <= n <= Length[v] && IntegerQ[n];


nthDifference2[v_List, n_Integer] :=

     Nest[ListCorrelate[{-1,1},#]&,v,n] /;

       0   <= n <= Length[v];


nthDifferenceList2[v_List, n_:Length[v]] :=

     NestList[ListCorrelate[{-1,1},#]&,v,n] /;

       0 <= n <= Length[v] && IntegerQ[n];



v = Table[Random[], {100000}];



d1 = nthDifferenceList1[v];//Timing



{0.38 Second,Null}



d2 = nthDifferenceList2[v];//Timing



{0.28 Second,Null}



d1==d2



True



Bob Hanlon




  • Prev by Date: Re: Symbols and Lists
  • Next by Date: Re: Solving a system of Inequalities
  • Previous by thread: Re: nth differences
  • Next by thread: Re: Re: nth differences