Re: how to iterate

• To: mathgroup at smc.vnet.net
• Subject: [mg65988] Re: how to iterate
• From: "Borut Levart" <BoLe79 at gmail.com>
• Date: Tue, 25 Apr 2006 05:19:29 -0400 (EDT)
• References: <e2i987\$9fc\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```I would iterate with a recursive definition, like this:

f[n_] := (f[n - 1] + f[n - 2] + 1)/f[n - 3];
f[1] = 1;
f[2] = 2;
f[3] = 3;

In[5]:=
f[10]

Out[5]=
2

(Valuating at: 1 ... 23)

In[8]:=
AbsoluteTiming[f/@Range[23]]

Out[8]=
{2.37 Second, {1, 2, 3, 6, 5, 4, 5/3, 4/3, 1, 2, 3, 6, 5, 4, 5/3, 4/3,
1, 2, 3, 6, 5, 4, 5/3}}

Note the calculation time. - Why does it take that much? For an initial
n, the expression inflates recursively, making n smaller, until n drops
below 3, when specific values are used. For a new n, the story is
similar. You can't get far like this.

You can make it faster by storing the known values along the way. With
a slight modification of the above definition: in addition to
SetDelayed, ":=", a normal Set, "=", is used, which stores the values
along the way, and that are later. You calculate g[4] for example, the
result is stored, and used when you want to calculate g[5], and so on.
Calculating from 4 on, one by one, nothing is truly "recursive"
anymore. But you can go far now.

g[n_] := g[n] = (g[n - 1] + g[n - 2] + 1)/g[n - 3];
g[1] = 1;
g[2] = 2;
g[3] = 3;

In[45]:=
AbsoluteTiming[g/@Range[2006];]

Out[45]=
{0.0468750 Second,Null}

Bye,
Borut Levart
Slovenia

```

• Prev by Date: Re: how to iterate
• Next by Date: NDSolve
• Previous by thread: Re: how to iterate
• Next by thread: Re: how to iterate