Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

On the implementation of the Fibonacci seq.

Name: Anonymous 2008-04-17 14:00

We all enjoy showing off how elegant our implementation of the Fibonacci sequence is in Haskell or Scheme or whatever.  But, frankly, they suck.  Even if you're using tail recursion to avoid fucking up the stack it's still terribly inefficient.

Here is the correct way to implement the Fibonacci sequence (in Scheme):
(define (fibonacci x)
    (let  ((phi (/ (+ 1 (sqrt 5)) 2)))
    (+ (/ (+ (expt phi x) (expt (- 1 phi) (- x 2))) (+ (expt phi 2) 1)) (/ (- (expt phi (- x 1)) (* phi (expt (- 1 phi) (- x 2)))) (+ (expt phi 2) 1)))))

Name: Anonymous 2008-04-17 14:33

>>1
[1]> (defun fibonacci (x)
    (let  ((phi (/ (+ 1 (sqrt 5)) 2)))
    (+ (/ (+ (expt phi x) (expt (- 1 phi) (- x 2))) (+ (expt phi 2) 1)) (/ (- (expt phi (- x 1)) (* phi (expt (- 1 phi) (- x 2)))) (+ (expt phi 2) 1)))))
FIBONACCI
[2]> (fibonacci 1)
1.0
[3]> (fibonacci 3)
2.0
[4]> (fibonacci 4)
3.0000005
[5]> (fibonacci -1)
0.99999994
[6]> (fibonacci 183)
7.8569633E37
[7]> (fibonacci 184)

*** - floating point underflow
The following restarts are available:
ABORT          :R1      ABORT
Break 1 [8]>

Oh, my. Here's how I would implement a function with identical output and range in C:
float fibonacci(int n) {
        return fibonacci_table[n];
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List