MathGroup Archive 2006

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

Search the Archive

Re: Suggestions for translating a Do[] loop ...


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


  • Prev by Date: Pure function in a pure function (again)
  • Next by Date: notebook interface: how make the cursor to be a 'block' cursor instead of the default?
  • Previous by thread: Re: Suggestions for translating a Do[] loop ...
  • Next by thread: Re: Suggestions for translating a Do[] loop ...