define a sequence



> Is there a way to define a sequence in maxima by recurrence?

u[0]: 5$
u[n] := 3*u[n-1]+2$

u[4] => 485

Note that individual elements are defined by *setting* them using the
":" operator, and calculation rules are defined by *defining* them
using the ":=" operator in the form u[n]:=... and not u[n+1]:=....

A few more examples:

v[0]:0$
v[n]:=v[n-1]^2*x+1

u[-5] => ... error (infinite recursion)

u[0.0] => ... error (infinite recursion)
      Maxima tests for exact identity, not equality

Maxima *caches* intermediate results, so:

t[0]:1$
t[1]:1$
t[n]:=t[n-1]+t[n-2]$

Calculating t[n] takes O(n) time, not O(2^n) time, so t[100] is
calculated quickly.

But beware!:  This means that if you want to change the definition of
t, you must first "kill" it so that Maxima forgets the cached results.

w[0]:0$
w[n]:=w[n-1]^3+1$
w[3] => 9    OK

Now try changing w[0]

w[0]:1$

w[3] => 9    Oops!

kill(w)$
w[n]:=w[n-1]^3+1$
w[0]:1$
w[3] => 730  OK

The calculations can be symbolic as well as numeric:

q[0]:1$ q[1]:1$
q[n]:=q[n-1]*a+q[n-2]*b$
q[3] => a*(b+a)+b
q[5] => a*(a*(a*(b+a)+b)+b*(b+a))+b*(a*(b+a)+b)

ratsimp(q[5]) => (2*a+1)*b^2+(a^3+3*a^2)*b+a^4
expand(q[5]) =>  2*a*b^2+b^2+a^3*b+3*a^2*b+a^4

Or even:

q[0]:0$ q[a]:a0$ q[b]:b0$
q[x]:=q[divide(x,a)[1]]*q[divide(x,b)[1]]+1;
q[a^3+b^3] => 2
q[a^3+b^3*(a+1)] => (a0+1)*(b0+2)+1
q[(a+b)^3] => 26
q[(a+b)^4] => 677