Re: Re: nth differences

• To: mathgroup at smc.vnet.net
• Subject: [mg39888] Re: [mg39878] Re: [mg39852] nth differences
• From: Dr Bob <drbob at bigfoot.com>
• Date: Sun, 9 Mar 2003 18:39:30 -0500 (EST)
• References: <200303091030.FAA07545@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Or:

nthDifferenceList3[v_List] := nthDifferenceList3[v, Length@v - 1]
nthDifferenceList3[v_List, n_Integer] /; 0 <= n < Length[v] :=
NestList[ListCorrelate[{-1, 1}, #] &, v, n]

Bobby

On Sun, 9 Mar 2003 05:30:30 -0500 (EST), <BobHanlon at aol.com> wrote:

>
> 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
>
>
>
>

--
majort at cox-internet.com
Bobby R. Treat

```

• Prev by Date: Re: How to convert string to variable name
• Next by Date: EllipticTheta error message
• Previous by thread: Re: nth differences
• Next by thread: Re: nth differences