Home > Uncategorized > Thoughts on Fibonacci Sequence Generation

Thoughts on Fibonacci Sequence Generation

March 22nd, 2009 Leave a comment Go to comments

So, a common interview question I’ve been asked is to write a function that will return the nth number in the Fibonacci Sequence. I think the question is meant to test two things: first, have you retained enough math to know what the Fibonacci sequence is; and second, do you know how to write a recursive function. Last week in my Combinatorics class (this is my Spring break, why am I writing this??), my professor introduced a closed form formula for calculating the nth number in the Fibonacci sequence. This is why I’m writing this now – when I saw the formula, I thought it’d be fun to memorize the formula, then whip it out in those interview questions. Not that I’ll ever get a chance now that I have a job lined up, but that’s another matter.

The formula goes like this:

where (the golden ratio).

I haven’t spent much time reading over the Wikipedia page, and we didn’t spend any time in class on the derivation… but it’s interesting that given integer inputs, the function produces integer outputs even though the square root of 5 is used throughout.

I was thinking to myself, “What would make the most sense in a programming context?” The answer wasn’t (and still isn’t) immediately clear. In the future I intend to do an actual comparison of three different methods of generating the nth number in the Fibonacci sequence (Closed form, recursive, and non-recursive). At first glance, for very small n the recursive and non-recursive forms should beat the closed form. For large n, the closed form should dominate the other two methods with the non-recursive method being faster than the recursive method.

One downside I see to the closed form method is error propagation – even with integer inputs, I would still expect a need to round to the nearest integer due to the small roundoff error incurred by using floats/doubles for the golden ratio.

Categories: Uncategorized Tags: ,
  1. No comments yet.
  1. No trackbacks yet.