HomeSearch

Python Fibonacci Sequence

This Python page computes Fibonacci sequences with an iterative method. It uses a for-loop and the range sequence.
Fibonacci. In 1202, Fibonacci published his sequence. The Fibonacci sequence helped with bookkeeping and charging interest on loans.
Algorithms. We can compute this sequence iteratively, with no recursion. To display a list of Fibonacci numbers, we can make just one iteration through them.
First program. To compute the Fibonacci sequence, we must sum the previous two numbers. This value becomes the next number for the sequence.

Variable: A temporary variable "temp" is used to store the previous value for later use.

Range: We use range() to loop over the entire numeric range to the desired Fibonacci number.

Range

Note: We do not need recursion for a Fibonacci sequence. Iteration, with a temporary variable, works as well—and is likely faster.

Python program that computes Fibonacci sequence def fibonacci(n): a = 0 b = 1 for i in range(0, n): temp = a a = b b = temp + b return a # Display the first 15 Fibonacci numbers. for c in range(0, 15): print(fibonacci(c)) Output 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Display. This method displays Fibonacci numbers as it goes along. For creating a list of Fibonacci numbers, this approach is faster. Just change the "print" statement to a list append call.

Tip: Using lookup tables or "memoizing" math computations is usually faster for nontrivial requirements.

Memoize

List: To access small Fibonacci numbers quickly, store them in a list and just reuse that list when required.

List
Python program that displays Fibonacci sequence def fibonacci2(n): a = 0 b = 1 for i in range(0, n): # Display the current Fibonacci number. print(a) temp = a a = b b = temp + b return a # Directly display the numbers. fibonacci2(15) Output 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Validation. I checked the output of this Python program against Wikipedia (which never has errors). The Fibonacci sequence correctly begins with 0, 1, 1 and 2.

Zero: Fibonacci himself did not include the 0, but modern scientists do. It is best to side with modernity.

Tip: I recommend checking as many sources as possible when researching. This includes websites other than this one.

But: Don't spend the whole day browsing Wikipedia if you are doing something important.

Quote: Fibonacci began the sequence not with 0, 1, 1, 2, as modern mathematicians do but with 1, 1, 2.

Fibonacci: Wikipedia
A summary. Fibonacci sequences are often used to predict financial markets. Whether anyone can predict financial markets reliably is debatable.
The sequence itself, though, is simple and easy to iteratively compute. Recursion is not necessary. Using a cache (like a list) of numbers would be worthwhile for performance.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls