Re: Simple recursive assignment

• To: mathgroup at smc.vnet.net
• Subject: [mg16028] Re: [mg15996] Simple recursive assignment
• From: "Wolf, Hartmut" <hwolf at debis.com>
• Date: Sat, 20 Feb 1999 02:52:12 -0500
• Organization: debis Systemhaus
• References: <199902190827.DAA18900@smc.vnet.net.>
• Sender: owner-wri-mathgroup at wolfram.com

```Ciao Peltio,

Peltio schrieb:
>
> Can someone spare a little time for a trivial question?
>
> The assignement
>     a[0]=1.;
>     a[1]=2.;
>     a[n_]:=a[n]=a[n-1]-a[n-2]/n
> works fine, all right...
>     a[5]
>         0.291667
>

equally fine will work that

In[4]:=b[0]=1.;
b[1]=2.;

In[5]:=expr[n_]:= b[n-1]-b[n-2]/n

In[6]:=b[n_]:=b[n]=expr[n]

In[7]:=b[5]
Out[7]=0.291667

but not

>     expr=b[n-1]-b[n-2]/n;
>
>     b[0]=1;
>     b[1]=2;
>     b[n_]:=b[n]=expr
>
>     b[3]
>         \$RecursionLimit::reclim: etc.
>

Why? From where shall expr get it's value for n? Case 1: n is just a
Symbol with no value. Then if you call b[3] then you call expr, and that
calls b[n-1] and b[n-2] and n hasn't got a value! which means calling
expr, which means calling b[n-1] and b[n-2] with the *same* n! (if n had
a value before, say 5, then expr is defined as b[4]-b[3]/5 and b[4] is
the same as expr as is also b[3]) ad infinitum!

But if you do the following, you will succeed:

In[9]:= Remove[b, expr, n]
In[10]:= b[0]=1.;
b[1]=2.;
In[11]:= expr= b[n-1]-b[n-2]/n;

In[12]:= b[nn_]:= b[nn]=Block[{n=nn}, expr]

In[13]:= b[5]
Out[13]= 0.291667

(Just a remark: if you use (n=nn; expr) instead of Block[...] the you
will also terminate, but get a wrong result. Can you see why?)

ciao, Hartmut

H. Wolf, debis Systemhaus, Darmstadt, Germania
=======[mailto:hwolf at debis.com]=======

```

• Prev by Date: Re: Simple recursive assignment
• Next by Date: Re: Must Play[] generate a graphic?
• Previous by thread: Simple recursive assignment
• Next by thread: Re: Simple recursive assignment