Re: Suggestions for translating a Do[] loop ...
- To: mathgroup at smc.vnet.net
- Subject: [mg69791] Re: Suggestions for translating a Do[] loop ...
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sat, 23 Sep 2006 04:44:40 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <eevtpj$hfr$1@smc.vnet.net>
David Annetts wrote:
> Hi,
>
> Given that a, b & r are lists of the same length, can anyone suggest a
> translation of the following Do[] loop to something functional? It looks
> like an ideal application for Fold, but for me, the loop going backwards is
> really obscuring things.
>
> The loop is
>
> Do[
> r[[j]] = a[[j]] * (b[[j]] + r[[j + 1]]) / (1 + b[[j]] * r[[j
> + 1]]),
> {j, Length@a - 1, 1, -1}
> ];
>
> with r[[Length@a]] = 0.
>
> Many thanks,
>
> Dave.
>
Dave,
First, notice that if we reverse the lists a, b, and r, we can write the
Do loop "from the beginning" as
Do[r[[j]] = a[[j]]*((b[[j]] + r[[j - 1]])/(1 + b[[j]]*r[[j - 1]])), {j,
2, Length[a], 1}];
Second, the initial values of the list r -- except 0 -- are not used
during the computation.
Third, what we need is FoldList and a starting value of 0 to build the
list r.
In[1]:=
a = Range[11];
b = Range[5, 15];
{a, b} = Rest /@ Reverse /@ {a, b};
Reverse[FoldList[#2[[1]]*((#2[[2]] + #1)/(1 + #2[[2]]*#1)) & , 0,
Transpose[{a, b}]]]
Out[4]=
{25357030627/34045828151, 6036337922/3864138541, 576190351/406996435,
498170924/175771447,
20343315/13024927, 1414446/294913, 904463/687499, 61944/6115,
459/607, 140, 0}
Result we can compare to the original code
In[5]:=
a = Range[11];
b = Range[5, 15];
r = Range[20, 30];
r[[Length[a]]] = 0;
Do[r[[j]] = a[[j]]*((b[[j]] + r[[j + 1]])/(1 + b[[j]]*r[[j + 1]])), {j,
Length[a] - 1, 1, -1}];
r
Out[10]=
{25357030627/34045828151, 6036337922/3864138541, 576190351/406996435,
498170924/175771447,
20343315/13024927, 1414446/294913, 904463/687499, 61944/6115,
459/607, 140, 0}
Regards,
Jean-Marc