View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Fibonacci Series in Python

Updated on 16/04/20256,168 Views

The Fibonacci series is one of the most fascinating mathematical sequences with applications spanning from nature and art to computer algorithms and financial markets. This tutorial will help you implement the Fibonacci series in Python using multiple methods. It covers basic iterative techniques as well as more advanced optimization strategies for better performance. Whether you're a beginner or experienced, you'll find useful examples to improve your programming skills.

What is the Fibonacci Sequence?

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence typically starts with 0 and 1, and continues infinitely: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...

Mathematically, it can be defined as:

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n > 1

This simple recursive definition creates a pattern commonly found in nature, like leaves, pinecones, and sunflowers. You can also see these spiral patterns in galaxies, showing how often Fibonacci appears in the real world.

Expand your expertise in AI with an Executive Programme, perfect for leaders in tech-driven industries.

How to Print Fibonacci Series in Python

Let's compare their strengths and limitations by exploring different methods to implement the Fibonacci sequence in Python.

Method 1: Iterative Approach

Problem Statement: Generate the first n numbers in the Fibonacci sequence using an iterative approach, which is ideal for larger sequences due to its efficiency.

def fibonacci_iterative(n):

# Initialize the first two terms
    a, b = 0, 1
    
    # Check if n is valid
    if n <= 0:
        return "Please enter a positive integer"
    elif n == 1:
        return [0]
    
    # Generate Fibonacci sequence
    fibonacci_sequence = [0, 1]
    for i in range(2, n):
        c = a + b
        fibonacci_sequence.append(c)
        # Update values for next iteration
        a, b = b, c
    
    return fibonacci_sequence

# Print first 10 Fibonacci numbers
result = fibonacci_iterative(10)
print(result)

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The iterative approach avoids redundant calculations by storing each value once, making it the most efficient method with time complexity O(n) and space complexity O(n).

Method 2: Recursive Approach

Problem Statement: Implement the Fibonacci sequence using recursion, which directly mirrors the mathematical definition F(n) = F(n-1) + F(n-2) but comes with performance limitations.

def fibonacci_recursive(n):

    # Base cases
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        # Recursive case: sum of previous two Fibonacci numbers
        return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

# Print first 10 Fibonacci numbers
result = [fibonacci_recursive(i) for i in range(10)]
print(result)

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

While this recursive implementation is elegant and closely follows the mathematical definition, it performs redundant calculations and has exponential time complexity O(2^n), making it impractical for values larger than 40.

Method 3: Dynamic Programming

Problem Statement: Implement the Fibonacci sequence using dynamic programming to eliminate repetitive calculations by storing previously computed values in an array.

def fibonacci_dp(n):

# Create an array to store Fibonacci numbers
    fib = [0] * (n + 1)
    
    # Base cases
    if n >= 1:
        fib[1] = 1
    
    # Calculate using bottom-up approach
    for i in range(2, n + 1):
        fib[i] = fib[i - 1] + fib[i - 2]
    
    return fib[:n]

# Print first 10 Fibonacci numbers
result = fibonacci_dp(10)
print(result)

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The dynamic programming approach builds the solution incrementally from the bottom up, storing each Fibonacci number exactly once and eliminating the redundant calculations of recursion while maintaining O(n) time complexity.

Unlock new career opportunities in data science with an MS online degree and Executive Diploma from IIITB.

Optimizing Fibonacci Calculations

For applications requiring frequent Fibonacci calculations, optimization becomes crucial.

Using Memoization

Problem Statement: Optimize the recursive Fibonacci implementation using memoization to cache previously calculated values, enabling efficient calculation of large Fibonacci numbers.

def fibonacci_memo(n, memo={}):
    # Check if value already calculated
    if n in memo:
        return memo[n]
    
    # Base cases
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    
    # Calculate and store result in memo dictionary
    memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)
    return memo[n]

# Calculate 50th Fibonacci number efficiently
result = fibonacci_memo(50)
print(f"The 50th Fibonacci number is: {result}")

Output:

The 50th Fibonacci number is: 12586269025

Memoization transforms the inefficient O(2^n) recursive algorithm into an efficient O(n) solution by eliminating redundant calculations while preserving the intuitive recursive structure.

Using Python's Built-in Cache

Problem Statement: Implement a clean and efficient Fibonacci calculator using Python's built-in LRU (Least Recently Used) cache decorator to automatically manage memoization.

from functools import lru_cache
@lru_cache(maxsize=None)  # No limit on cache size
def fibonacci_cached(n):
    # Base cases
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        # Recursive case with automatic caching
        return fibonacci_cached(n-1) + fibonacci_cached(n-2)

# Calculate 100th Fibonacci number efficiently
result = fibonacci_cached(100)
print(f"The 100th Fibonacci number is: {result}")

Output:

The 100th Fibonacci number is: 354224848179261915075

The lru_cache decorator from Python's standard library provides a simple one-line solution for memoization. It automatically handles the caching details and makes the code elegant and production-ready.

Real-World Applications of Fibonacci Series

The Fibonacci sequence extends far beyond mathematical curiosity, finding applications in various domains:

1. Financial Markets and Trading Algorithms

In technical analysis of financial markets, Fibonacci retracement levels (38.2%, 50%, 61.8%) are widely used to identify potential support and resistance levels. These are derived from the Fibonacci sequence and the golden ratio (approximately 1.618).

Below is a Python function that calculates the Fibonacci retracement levels based on a given high and low price:

def fibonacci_retracement(high_price, low_price):
    diff = high_price - low_price
    levels = {
        "0%": low_price,
        "23.6%": low_price + 0.236 * diff,
        "38.2%": low_price + 0.382 * diff,
        "50%": low_price + 0.5 * diff,
        "61.8%": low_price + 0.618 * diff,
        "100%": high_price
    }
    return levels

# Calculate Fibonacci retracement levels for a stock
high = 150.75
low = 120.25
print(fibonacci_retracement(high, low))Output:

{
    '0%': 120.25,
    '23.6%': 127.448,
    '38.2%': 131.901,
    '50%': 135.5,
    '61.8%': 139.099,
    '100%': 150.75
}

2. Computer Science: Search Algorithms and Data Structures

The Fibonacci search technique is used in sorted arrays to find a target value using a divide and conquer approach. It's particularly efficient for arrays that can't be randomly accessed, like tape drives.

3. Natural Patterns and Growth Models

The Fibonacci sequence models many natural phenomena, from the arrangement of leaves on a stem (phyllotaxis) to population growth models. Researchers use these patterns to understand biological systems and predict growth patterns.

Visualizing the Fibonacci Sequence

The Fibonacci sequence appears widely in nature, forming spiral patterns seen in sunflowers, shells, and galaxies. This visualization, created using Python, shows how the sequence translates into a spiral, revealing the mathematical beauty behind natural growth and design.

To create a simple visualization of the Fibonacci spiral in Python, you can use the matplotlib library:

import matplotlib.pyplot as plt
import numpy as np

def fibonacci_spiral(n):
    # Generate Fibonacci numbers
    fib = [0, 1]
    for i in range(2, n):
        fib.append(fib[i-1] + fib[i-2])
    
    # Create the spiral
    x = [0] * n
    y = [0] * n
    angle = 0
    
    for i in range(1, n):
        angle += np.pi/2
        radius = np.sqrt(fib[i])
        x[i] = x[i-1] + radius * np.cos(angle)
        y[i] = y[i-1] + radius * np.sin(angle)
    
    # Plot the spiral
    plt.figure(figsize=(10, 10))
    plt.plot(x, y, 'b-')
    plt.plot(x, y, 'ro')
    plt.grid(True)
    plt.axis('equal')
    plt.title('Fibonacci Spiral')
    plt.savefig('fibonacci_spiral.png')
    plt.show()

# Generate a Fibonacci spiral with 20 points
fibonacci_spiral(20)

Output:


Conclusion

The Fibonacci sequence is a cool example of how math shows up in nature and computer programs. In this tutorial, we explored different ways to create a Fibonacci series program in Python, starting from simple approaches like loops to smarter methods such as memoization and dynamic programming.

Learning how to write a Fibonacci series program in Python not only improves your Python skills but also helps you understand how to design efficient algorithms. Fibonacci numbers appear in many fields like finance, coding challenges, and nature and mastering how to generate them builds a strong foundation for solving a wide range of problems.

As you continue learning Python and algorithms, remember that even a simple concept like the Fibonacci series can reveal deep insights into how math and computing work together!

Frequently Asked Questions

1. What is the Fibonacci series?

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1.

2. Why is the Fibonacci sequence important in Python programming?

The Fibonacci sequence serves as an excellent example for teaching programming concepts like recursion, dynamic programming, and algorithm optimization.

3. How can I calculate the nth Fibonacci number efficiently?

For efficient calculation, use either the iterative approach, dynamic programming, or memoized recursion with the lru_cache decorator.

4. What is the time complexity of different Fibonacci implementations?

  • Naive recursive: O(2^n)
  • Iterative: O(n)
  • Dynamic programming: O(n)
  • Memoized recursive: O(n)

5. Can I generate Fibonacci numbers in constant time?

Yes, using Binet's formula: F(n) = (φⁿ - (1-φ)ⁿ)/√5, where φ is the golden ratio (1.618...), though this may have floating-point precision issues for large n.

6. What is the relationship between Fibonacci numbers and the golden ratio?

As n increases, the ratio of consecutive Fibonacci numbers (F(n+1)/F(n)) approaches the golden ratio (approximately 1.618).

7. How can I optimize memory usage when generating Fibonacci numbers?

If you only need the nth Fibonacci number (not the entire sequence), you can use just three variables instead of an array, reducing space complexity to O(1).

8. Are there Fibonacci variations that start with different numbers?

Yes, the Lucas sequence (2, 1, 3, 4, 7, 11, ...) and other generalized Fibonacci sequences follow the same recursive pattern but start with different values.

9. How are Fibonacci numbers used in algorithm analysis?

Fibonacci heaps, used in certain graph algorithms like Dijkstra's, achieve better amortized running time than binary heaps for certain operations.

10. How do Fibonacci numbers relate to Pascal's triangle?

Sum the shallow diagonals in Pascal's triangle to obtain Fibonacci numbers.

11. Can Fibonacci calculations overflow in Python?

Python handles arbitrary-precision arithmetic automatically, so Fibonacci calculations won't overflow like they might in languages with fixed-size integers.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.