Fibonacci numbers

Benchmark created by Mathias Bynens on


Description

Let’s compare two different methods that will return a Fibonacci number for a given index.

The first function, fibonacci1(), doesn’t use any loops or recursion. However, it can only handle indexes up to 1474:

> fibonacci1(1474)
4.992254605477748e+307
> fibonacci1(1475)
Infinity

Edit: Hmm, it seems to return inaccurate results starting at n = 76. See http://jsfiddle.net/mathias/CFWGc/.

The second function, fibonacci2(), uses a loop and an array to calculate the result. It should be able to handle indexes up to 1476.

> fibonacci2(1475)
8.077637632156222e+307
> fibonacci2(1476)
1.3069892237633987e+308
> fibonacci2(1477)
Infinity

Preparation HTML

<script>
  // No recursion or looping, just math
  function fibonacci1(n) {
    return Math.round(Math.pow((Math.sqrt(5) + 1) / 2, Math.abs(n)) / Math.sqrt(5)) * (n < 0 && n % 2 ? -1 : 1);
  }
  
  // Using a loop and an array
  function fibonacci2(n) {
    var i, fibs = [0, 1];
    for (i = 0; i++ < n;) {
      fibs.push(fibs[0] + fibs[1]);
      fibs.shift();
    }
    return fibs[0];
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
No recursion or looping
fibonacci1(42);
ready
Using a loop and an array
fibonacci2(42);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Mathias Bynens on