
A program to compute the nth Fibonacci number - ColinWright
https://github.com/raganwald/homoiconic/blob/master/2008-12-12/fibonacci.md
======
jlarocco
Way too much work.

    
    
      def fib_binet(n)
        a = (1+Math.sqrt(5))**n
        b = (1-Math.sqrt(5))**n
        c = (2**n)*Math.sqrt(5)
        return ((a-b)/c).truncate()
      end
    
      def fib2(n)
        a = Math.sqrt(5)
        return ((1/a)*(((1+a)/2)**n)).round()
      end
      (0..20).each do | i |
        puts fib_binet(i)
        puts fib2(i)
      end

~~~
pavpanchekha
1) You don't really need the (b) term. (1 - \phi) is on the order of .5, so if
you round the result of ((a - b) / c) instead of truncating it, you can ignore
that term.

2) How long are your floating point numbers? You code works for n up to 71,
but no further. The linked example works for any n.

Every time Fibonacci is discussed, someone brings up the Binet formula. If I'm
interviewing for a position that requires any sort of numeric coding, this is
a reason not to hire -- it demonstrates you don't know the first things about
floating point.

~~~
xyzzyz
Binet formula needs not to be implemented using floating point numbers:

<https://github.com/xyzzyz/FibBinet>

------
huggah
This is neat, and a solution that I hadn't seen before. But the author doesn't
seem to be aware that finding the nth Fibonacci number is an O(1) problem:
[http://en.wikipedia.org/wiki/Fibonacci_number#Closed-
form_ex...](http://en.wikipedia.org/wiki/Fibonacci_number#Closed-
form_expression)

Even the page the author links to is doing a great deal too much work!

~~~
sp332
That's probably faster, but it's not O(1). Calculating sqrt(5) to the needed
precision, and raising phi to the n power, are not O(1).

~~~
ranit8
> Calculating sqrt(5) to the needed precision...

I think this one could be optimized by precomputing and storing (1 + sqrt(5))
at the highest precision available.

~~~
sp332
If you want to find an arbitrarily high F(n), you will need an arbitrarily
high precision of sqrt(5).

------
asselinpaul
Another good way:

def fib(number): if number == 0: return 0 elif number == 1: return 1 else:
return fib(number-1) + fib(number-2)

print fib(10)

