In engineering problems, I am always seeing many recursion formula
.
For instance, In the book "The NURBS book", I discovered many recursion formula
Fibonacci $$f(n+2)=f(n+1)+f(n)$$
deCasteljau algorithm $$\vec{P}_{k,i}(u_0)=(1-u_0)\vec{P}_{k-1,i}(u_0)+u_0\vec{P}_{k-1,i+1}(u_0)$$
Horner
And so on.
Previously, I know many Mathematica user used the solution as beow to code.
fib[n_] := fib[n] = fib[n - 1] + fib[n - 2];
fib[1] = fib[2] = 1;
fib[200]
280571172992510140037611932413038677189525
However, when n
became larger, like n=300
fib[300]
$RecursionLimit::reclim: Recursion depth of 256 exceeded. >>
The built-in funcion Fibonacci
can give the result normally.
Fibonacci[300]
222232244629420445529739893461909967206666939096499764990979600
Question:
Is it possible to have a general(uniform) method
(Namely, like Funcion Programing paradigm like Nest,NestList,FoldList) to deal with these recursion formula in Mathematica?
Summarize
Firstly, thanks for the help of igor Rivin,m_goldberg, bbpdqn.
(Efficiency test)
IgorRivin = {{0, 1}, {1, 1}};
fibIgorRivin[n_] := MatrixPower[IgorRivin, n][[2, 1]]
fibIgorRivin[1000000] // AbsoluteTiming // First
0.2900166
fibGoldberg[n_Integer /; n > 0] := fibAux[1, 0, n]
fibAux[_, b_, 0] := b
fibAux[a_, b_, n_] := fibAux[a + b, a, n - 1]
$IterationLimit::itlim: Iteration limit of 4096 exceeded. >>
fibUbpdqn[1] := 1;
fibUbpdqn[2] := 1;
fibUbpdqn[n_] :=
First@Nest[{#[[1]] + #[[2]], #[[1]]} &, {1, 1}, n - 2]
fibUbpdqn[1000000] // AbsoluteTiming // First
15.2288711
Fibonacci[1000000] // AbsoluteTiming // First
0.2370136
RecursionLimit
to a higher value. For example$RecursionLimit = 1000
$\endgroup$$RecursionLimit
is 1024. $\endgroup$RSolve
which can determine closed form representations for many recursive equations. $\endgroup$