Home
Map
Fibonacci SequenceCompute Fibonacci sequences with an iterative method. Use a for-loop and the range sequence.
Python
This page was last reviewed on Mar 20, 2023.
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.
Info A temporary variable "temp" is used to store the previous value for later use.
Note We use range() to loop over the entire numeric range to the desired Fibonacci number.
while
Note 2 We do not need recursion for a Fibonacci sequence. Iteration, with a temporary variable, works as well—and is likely faster.
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))
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
Tip 2 To access small Fibonacci numbers quickly, store them in a list and just reuse that list when required.
String List
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)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 20, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.