

Why is Fibonacci misimplemented so often? - globalrev

Why is it that so many times, even among good programmers, the Fibonacci function is misimplemented?<p>Here it is from the OCaml tutorial:<p>&#60;&#60;#let rec fib n =
  #  if n &#60; 2 then 1 else fib(n-1) + fib(n-2);;
  val fib : int -&#62; int = &#60;fun&#62;<p><pre><code>  #fib 10;;
  - : int = 89</code></pre>
&#62;&#62;<p>Finonacci 0 is 0, not 1.
Thus: Fibonacci 10 is 55.<p>Corrected:<p># let rec fibo n =
#  if n &#60; 2 then if n ==1 then 1 else 0 else fibo(n-1) + fibo(n-2);;
val fibo : int -&#62; int = &#60;fun&#62;
# fibo 12;;
- : int = 144
# fibo 10;;
- : int = 55
#<p>(And yes it is a superslow exponential implementation but that is not the point here.)
======
yan
I think that's the case because the Fibonacci sequence isn't interesting as a
sequence itself to most developers, but as an example of basic recursion. And
as an example of basic recursion, you can have a base case be slightly off
without misrepresenting what the essence is.

~~~
silverlake
you're right, but you can implement the real fib by returning N instead of 1:

let rec fib n = if n < 2 then n else fib(n-1) + fib(n-2)

------
MaysonL
Perhaps because in the _original_ (Sanskrit) implementation, Fib(10) = 89?

<http://en.wikipedia.org/wiki/Fibonacci_number>

------
michael_dorfman
It's not only Fibonacci-- "off by one" errors are more common than you'd
think.

