Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2001

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

Search the Archive

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[0] = 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[1]:=r={0,1,2,3,4,5}
x=FoldList[#1(1+#2)&,1,r]

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

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

You can easily check the correctness of the result

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

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

Long lists of floating point numbers are processed very quickly

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

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

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

Verification

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

Out[6]= 1.88333 Second

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

Hope it helps


Adriano Pascoletti


  • Prev by Date: RE: array generated
  • Next by Date: Re: Has anybody gotten MathLink Modules to compile using Linux Mandrake 8.0
  • Previous by thread: Q: Recursion on a list
  • Next by thread: Re: Q: Recursion on a list