Fibonacci Series in Python

Fibonacci Series in Python

The Fibonacci series is a sequence of numbers in which each number is the sum of the two numbers before it. It is a sequence that can be seen frequently in mathematics, computer science, and even in nature. You must be wondering, if each number is the sum of two numbers before it, then from where does this series start? So, a Fibonacci sequence starts from 0 and 1 and then goes on forever in the said pattern.

In this article, you will learn about the Fibonacci series, its applications, ways to generate a Fibonacci Series in Python, and common errors in a Fibonacci program.

Table of Contents

What is the Fibonacci Sequence?

The Fibonacci sequence is a sequence of numbers that start with 0 and 1, and all the next numbers are the sum of the previous two numbers. A Fibonacci sequence looks like:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

This Fibonacci sequence has vast applications like data analysis, algorithm design, graphic designing, and even in nature like spirals in shells and flower patterns.

Properties of the Fibonacci Sequence

There are various properties of a Fibonacci series which makes it useful for mathematical and other fields. Below are some of these properties:

  • The basic property of a Fibonacci sequence is that each number in the series is the sum of two preceding numbers.
    Example:
    F(0) = 0, F(1) = 1
    F(2) = F(1) + F(0) = 1 + 0 = 1
    F(3) = F(2) + F(1) = 1 + 1 = 2
  • The ratio of two successive terms is always approximately the same which is 1.618. This ratio is called the Golden Ratio(ϕ).
    Example:
    F(11)/F(10) = 89/55 ≈ 1.618
    F(24)/F(23) = 46368/28657 ≈ 1.618
  • The sum of the first n terms of a Fibonacci sequence is F(n + 2) – 1.
    Example:
    By Formula:
    Sum of 6 terms is, F(6 + 2) – 1 => F(8) – 1 = 21 – 1 = 20

    By Calculation:
    => F(0) + F(1) + F(2) + F(3) + F(4) + F(5) + F(6)
    = 0 + 1 + 1 + 2 + 3 + 5 + 8 = 20
  • Every 3rd term of the Fibonacci sequence is divisible by 2, and every 4th term of the sequence is divisible by 3.
Beginner to Pro: Learn Python with Hands-On Projects
Enroll Now and Start Building Real-World Applications!
quiz-icon

How to Generate a Fibonacci Series in Python

Python provides various methods that allow its users to generate a Fibonacci series depending upon the use case of their program. Following are some of these methods:

Using Iterative approach

In this approach, you can use a loop to generate a Fibonacci series in Python. In this method, you can use a for loop or a while loop to generate a series.

1. Using a For Loop

One of the most common and easy-to-use methods in Python to generate a Fibonacci Series is by using a for loop.

Example:

#Python code to generate Fibonacci Series

def fib_for_loop(n):
    f_sequence = []
    x, y = 0, 1

    for _ in range(n):
        f_sequence.append(x)
        x, y = y, x + y
    return f_sequence

# Sample Input
n = 10

print("Fibonacci Series using For Loop:", fib_for_loop(n))
#Output: Fibonacci Series using For Loop: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Sample Input

n = 10
print("Fibonacci Series using For Loop:", fib_for_loop(n))
Output: Fibonacci Series using For Loop: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

2. Using a While Loop

Another easy-to-use method in Python to generate a Fibonacci series is using a while loop.

Example:

Python code to generate a Fibonacci Series

def fib_while_loop(n):
    f_sequence = []
    x, y = 0, 1
    counter = 0
    while counter < n:
        f_sequence.append(x)
        x, y = y, x + y
        counter += 1
    return f_sequence

Sample Input

n = 10
print("Fibonacci Series using While Loop:", fib_while_loop(n))
Output: Fibonacci Series using While Loop: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Using Recursive Approach

In this method, you can use a function that calls itself again and again to generate a Fibonacci series. 

Example:


# Python program to generate a Fibonacci Series
def f_recursive(n):

    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return f_recursive(n - 1) + f_recursive(n - 2)

# Sample Input
n = 10

f_sequence = [f_recursive(i) for i in range(n)]
print("Fibonacci Series using Recursion:", f_sequence)

#Output: Fibonacci Series using Recursion: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Dynamic Programming Approach

This is one of the faster approaches in Python to generate a Fibonacci series, as it holds the already computed data in a table to avoid repetitive computations.

Example:

#Python code to generate a Fibonacci Series

def f_dynamic_approach(n):
    if n <= 0:
        return []
    f_sequence = [0, 1]
    for a in range(2, n):
        f_sequence.append(f_sequence[a - 1] + f_sequence[a - 2])
    return f_sequence[:n]

#Sample Input
n = 10

print("Fibonacci Series using Dynamic Approach:", f_dynamic_approach(n))
#Output: Fibonacci Series using Dynamic Approach: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Using Python Generators

Python generators are memory efficient, so they don’t store all items in memory. They generate one number at a time and then remove it from memory. 

Example:

def fib_generator(n):
    x, y = 0, 1
    for _ in range(n):
        yield x
        x, y = y, x + y

# Sample Input
n = 10

print("Fibonacci Series using Python Generators:", list(fib_generator(n))
#Output: Fibonacci Series using Python Generators: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Using Libraries like NumPy

Python provides several libraries that can be used to make operations easier. NumPy library in Python can be used to generate a Fibonacci series.

Example:

# Python program to generate Fibonacci Series

import numpy as np
def fib_numpy(n):

    fibonacci_matrix = np.array([[1, 1], [1, 0]])

    def matrix_pow(matrix, power):

        result = np.identity(len(matrix), dtype=int)
        for _ in range(power):
            result = np.dot(result, matrix)
        return result
    return matrix_pow(fibonacci_matrix, n - 1)[0][0] if n > 0 else 0

# Sample Input
n = 10

fibonacci_sequence = [fib_numpy(i) for i in range(1, n)]
print("Fibonacci Series using NymPy Library:", fibonacci_sequence)

#Output: Fibonacci Series using NumPy Library: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Using Caching Method

Similar to the dynamic approach, the caching method in Python also stores already calculated values for future use. This helps in the repeated calculation of values. Caching is of two types:

1. Manual Caching

In this method, you can use a dictionary to store the computed values.

Example:

# Python program to generate Fibonacci Series
def fib_manual_cache(n, cache={}):

    if n in cache:
        return cache[n]

    if n <= 0:
        return 0

    elif n == 1:
        return 1

    else:
        cache[n] = fib_manual_cache(n - 1, cache) + fib_manual_cache(n - 2, cache)
        return cache[n]

# Sample Input

n = 10
f_sequence = [fib_manual_cache(i) for i in range(n)]
print("Fibonacci Series using Manual Cache:", f_sequence)

#Output: Fibonacci Series using Manual Cache: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

2. Using functools.lru_cache

Python provides a pre-defined tool functools.lru_cache to automatically perform the caching operation.

Example:

# Python program to generate Fibonacci Series

from functools import lru_cache
@lru_cache(maxsize=None)

def fib_lru_cache(n):
    if n <= 0:
        return 0

    elif n == 1:
        return 1

    else:
        return fib_lru_cache(n - 1) + fib_lru_cache(n - 2)

# Sample Input
n = 10

f_sequence = [fib_lru_cache(i) for i in range(n)]
print("Fibonacci Series using LRU Cache:", f_sequence)

#Output: Fibonacci Series using LRU Cache: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Visualizing the Fibonacci Sequence in Python

One of the most powerful ways to understand data and patterns is visualization. It helps in analyzing the growth of a Fibonacci sequence and its mathematical properties. To create plots and visual representations of a Fibonacci sequence, you can use Python libraries such as Matplotlib and Seaborn.

Steps for Visualization of the Fibonacci Sequence

You can follow the steps given below to visualize a Fibonacci sequence:

Step 1: Create a list of Fibonacci numbers using any of the methods explained above.

Step 2: Choose a visualization type from some common choices like line plots, bar graphs, or scatter plots.

Step 3: Now plot the sequence using any Python libraries like Matplotlib or Seaborn.

Example of a Line Plot:

#Python code to Visualize a Fibonacci Sequence

import matplotlib.pyplot as mplot
# Creating Function for Fibonacci numbers

def fib_sequence(n):
    f_sequence = [0, 1]

    for i in range(2, n):
        f_sequence.append(f_sequence[-1] + f_sequence[-2])
    return f_sequence

# Calling function to Generate Fibonacci numbers

n = 20
f_numbers = fib_sequence(n)

# Plotting the Fibonacci sequence on Line chart

mplot.figure(figsize=(10, 6))
mplot.plot(range(n), f_numbers, marker='o', linestyle='-', color='r')
mplot.title("Fibonacci Sequence Visualization")
mplot.xlabel("Index")
mplot.ylabel("Fibonacci Number")
mplot.grid(True)
mplot.show()

Output:

Example of a Scatter Plot:

#Python code to Visualize a Fibonacci Sequence
import matplotlib.pyplot as mplot

# Creating Function for Fibonacci numbers

def fib_sequence(n):
    f_sequence = [0, 1]

    for i in range(2, n):
        f_sequence.append(f_sequence[-1] + f_sequence[-2])
    return f_sequence

# Calling function to Generate Fibonacci numbers
n = 20
f_numbers = fib_sequence(n)
# Plotting the Fibonacci sequence on Scatter Plot

mplot.figure(figsize=(10, 6))
mplot.scatter(range(n), f_numbers, color='b', s=150)
mplot.title("Fibonacci Sequence - Scatter Plot")
mplot.xlabel("Index")
mplot.ylabel("Fibonacci Number")
mplot.grid(True)
mplot.show()

Output:

Learn Python - The Language of the Future!
Step into Tech with Python: Beginner-Friendly & Career-Boosting
quiz-icon

Common Errors in Fibonacci Programs and How to Fix Them

Developers can sometimes make mistakes that cause errors in a Fibonacci program, which can result in unexpected or no output. Below are some common errors and some solutions to resolve them:

1. Infinite Recursion in Recursive Functions

You might miss the base case while writing a recursive function for the generation of the Fibonacci sequence, this will result in infinite recursion. 

Solution:

  • Make sure you include a base case while writing a recursive function.

2. Recalculation of already computed Fibonacci numbers

If you write code that is not optimized, then your code might result in recalculation of the already computed Fibonacci numbers, which can cause computation delays.

Solution:

  • Use techniques like a dynamic programming approach to store already computed Fibonacci numbers.

3. Incorrect indexing in Iterative solutions

If you write code that follows incorrect indexing while generating a Fibonacci sequence, then it might result in logic errors or code crashes.

Solution:

  • Make sure the indices align with the logic of the Fibonacci sequence.

4. Using Incorrect Data Types

If you use an incorrect datatype like string or float while generating a Fibonacci sequence then it can result in TypeError or an unexpected behavior.

Solution:

  • Make sure you use the correct input datatype which is integer while writing code.

5. Errors in Boundary conditions

You might miss mentioning boundary conditions like n = 0 or n = 1 while writing a Fibonacci code.

Solution:

  • You must test the boundary conditions before executing the code, to avoid errors.

Real-world Applications of the Fibonacci Series

There are many real-world applications of the Fibonacci series across various domains. Some of these applications are:

  1. You can observe the Fibonacci patterns in natural phenomena such as the arrangement of flowers or leaves on the stem of a plant.
  2. You can see the use of Fibonacci numbers in algorithms and data structures.
  3. Many traders use the Fibonacci sequence to predict support and resistance levels in financial markets.
  4. Fibonacci numbers are also used in secure data transmission in crypto algorithms.
  5. Fibonacci sequences are used to determine dimensions for architectural structures.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusions

The Fibonacci sequence is not just a mathematical concept. It is used in various applications around the world like technology, nature, architectural structures, and art forms like music. In this blog, you have learned about various methods of generating a Fibonacci sequence in Python like using an Iterative approach, using recursive methods, using Python generators, and various Python libraries. You can create various visualization patterns like line charts or scatter plots to visualize Fibonacci sequences. If you want to explore more about Python programming you can enroll in Intellipaat’s Python Course and take a leap into Python World.

FAQs

1. What is a Fibonacci Series?

A Fibonacci series is a sequence of numbers that start with 0 and 1 and then each number is the sum of the preceding two numbers. 
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and so on…

2. What is the importance of a Fibonacci Series?

The Fibonacci series is very important in various applications in the real world like nature, art, cryptography, computer science, financial markets, etc.

3. What methods can be used to generate a Fibonacci sequence?

You can use various methods for generating a Fibonacci sequence in Python. Some of these methods are iteration, recursion, generators, dynamic programming approach, built-in libraries, etc.

4. Can we use a Fibonacci series in advanced technologies like Machine Learning?

Yes, you can efficiently use a Fibonacci series in machine learning for performing tasks like feature engineering, optimization of tasks, and performing time-series operations.

5. What is the difference between an iterative and recursive Fibonacci series?

Both methods are used for the generation of the Fibonacci series, but an iterative approach uses loops for faster computations while a recursive approach uses function calls to compute each term.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 26th Jan 2025
₹20,007
Cohort starts on 2nd Feb 2025
₹20,007

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.