Here are the first 14 Fibonacci numbers, starting with F(0):
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...
and various Common Lisp implementations for the computation of the nth element of the sequence, structured similarly to the Factorial page:
This loop-based implementation probably written by Nicolas Neuss (my.name@iwr.uni-heidelberg.de):
You can use multiple values for a truly recursive implementation:
A "successive squaring" method suggested in Structure and Interpretation of Computer Programs, which runs in a logarithmic number of steps:
Another successive squaring method based on these formulas: F(2n-1)=F(n)^2+F(n-1)^2, F(2n)=(2F(n-1)+F(n))*F(n). See the end of this section from the Wikipedia article, or see the same EWD note as above, In honour of Fibonacci by Edsger Wybe Dijkstra.
And now for something completely different, a generator version, inspired by a Python snippet.
Python | Lisp | Ruby | Javascript |
---|---|---|---|
def make_fib()
a = 0; b = 1
lambda {
v = a
a, b = b, a + b
v
}
end
or
and even easier
Q: In the Winston & Horn book, n for the two above functions is n+1. Is there some reason for NOT having e.g.
(expt (/ (- 1 (sqrt 5)) 2) (+ n 1)))
?
A: Some authors still use a deprecated definition of the Fibonacci sequence, the one that begins with 1, 1 instead of 0, 1. Please see the definition and especially the
closed form.
Also, most books that touch on this topic (Donald Knuth's TAOCP for instance).
Q: Do we have any reason to keep the first implementation instead of the second one based on the Binet formula? --Cornel
Caution: Due to limitations in floating-point representation precision, this last version works - (truncate (fib n)) is correct - only for n < 32.
From that point on, the error rises exponentially approximately like this: new_error = old_error * (5 / 3)
So, if for n = 32 the error is 1.25, for n = 99 the error is 4.2221247E14. I determined this using CLISP 2.33.2 under GNU Linux on IA32.
This can be improved by using 5.0d0 instead of 5, which ensures the use of
double-float. CLISP 2.33.2 computes correct values (using (round (fib n)) for
n ≤ 75.