TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Why is Fibonacci misimplemented so often?

3 pointsby globalrevalmost 17 years ago
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.)

3 comments

yanalmost 17 years ago
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.
评论 #274372 未加载
MaysonLalmost 17 years ago
Perhaps because in the <i>original</i> (Sanskrit) implementation, Fib(10) = 89?<p><a href="http://en.wikipedia.org/wiki/Fibonacci_number" rel="nofollow">http://en.wikipedia.org/wiki/Fibonacci_number</a>
michael_dorfmanalmost 17 years ago
It's not only Fibonacci-- "off by one" errors are more common than you'd think.