malina
malina

Reputation: 121

Recursive function definition in Mathematica

Mathematica can solve recursive equations using RSolve. Is it possible to have a function defined by a recurrence, regardless whether the recurrence can or cannot be solved analytically?

Upvotes: 2

Views: 11193

Answers (2)

Bobby Treat
Bobby Treat

Reputation: 101

I wondered for a moment what RecurrenceTable is good for, until I rewrote Sasha's example using NestList:

Rest@NestList[{1, 0} + First@# {1, Last@#} &, {1, 1}, 10][[All, -1]]

{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}

If the involvement of k (First@#) is complicated, RecurrenceTable could be far simpler.

Upvotes: 1

Sasha
Sasha

Reputation: 5954

Yes. Look at RecurrenceTable. One also can program to define a function by its recurrence equation, factorial being the simplest example.

In[94]:= fac[1] = 1;
fac[k_Integer?Positive] := k*fac[k - 1]

In[96]:= fac[10]

Out[96]= 3628800

In[97]:= Function[If[#1 == 1, 1, #1*#0[#1 - 1]]][10]

Out[97]= 3628800

In[100]:= RecurrenceTable[
 f[k] == k f[k - 1] && f[1] == 1, f, {k, 1, 10}]

Out[100]= {1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}

Upvotes: 7

Related Questions