       Re: Q: Recursion on a list

• To: mathgroup at smc.vnet.net
• Subject: [mg28896] Re: [mg28886] Q: Recursion on a list
• From: Adriano Pascoletti <pascolet at dimi.uniud.it>
• Date: Fri, 18 May 2001 01:13:01 -0400 (EDT)
• References: <200105170822.EAA02986@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

At 4:22 -0400 17-05-2001, msc wrote:
>I'm looking for an efficient method (i.e., with the use of an explicit loop)
>for the following problem. I am working with large lists (several thousand
>elements) of data. Denote one such list r. I would like to define a new list
>x such that:
>
>
>x = 1.0
>
>x[t] = x[t-1]*(1.0 + r[t])
>
>Can anyone suggest an efficient way?

Mark,

use FoldList[#1(1 + #2) &, 1, r].

In:=r={0,1,2,3,4,5}
x=FoldList[#1(1+#2)&,1,r]

Out={0,1,2,3,4,5}

Out={1,1,2,6,24,120,720}

You can easily check the correctness of the result

In:=(x[[#+1]]-x[[#]])/x[[#]]&/@Range[Length[r]]

Out={0,1,2,3,4,5}

Long lists of floating point numbers are processed very quickly

In:= r=Table[Random[],{10000}];

In:= Timing[x=FoldList[#1(1+#2)&,1,r]][]

Out= 0.45 Second
(on a PowerMac G3 - 300MHz)

Verification

In:= Timing[d=Chop[(x[[#+1]]-x[[#]])/x[[#]]-r[[#]]]&/@Range[Length[r]]][]
Shallow[d]

Out= 1.88333 Second

Out//Shallow= {0,0,0,0,0,0,0,0,0,0,\[LeftSkeleton]9990\[RightSkeleton]}

Hope it helps