Fibonacci Series in Python | Code, Algorithm & More

Analytics Vidhya Last Updated : 24 Oct, 2024
7 min read

The Fibonacci series in python is a mathematical sequence that starts with 0 and 1, with each subsequent number being the sum of the two preceding ones. In Python, generating the Fibonacci series is not only a classic programming exercise but also a great way to explore recursion and iterative solutions.

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

In this article, you will learn how to create the Fibonacci series in Python using different methods. We will show you how to make the Fibonacci series in Python using a function, a while loop, and a for loop. You will also see how to print the Fibonacci series in Python using recursion and without using a function. We’ll explain what the Fibonacci series means and how to find the sum of the series in Python. By the end, you will understand these methods clearly.

What is the Fibonacci Series?

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, typically starting with 0 and 1. The sequence is defined as:

Fibonacci Series in Python
Source: TecAdmin

Also Read: 90+ Python Interview Questions to Ace Your Next Job Interview in 2024

Mathematical Formula for the Fibonacci Sequence

The mathematical formula to calculate the Fibonacci sequence is: 

F(n) = F(n-1) + F(n-2)

Where:

  • F(n) is the nth Fibonacci number
  • F(n-1) is the (n-1)th Fibonacci number
  • F(n-2) is the (n-2)th Fibonacci number

Recursive Definition

The recursive definition of the Fibonacci series is dependent on the recursive system.

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

So, every number in the Fibonacci series is calculated by including the two numbers  before it. This recursive method continues generating the entire sequence, starting from  0 and 1.

Also Read: Top 10 Uses of Python in the Real World with Examples

Recursive Fibonacci Series in Python

Fibonacci numbers recursively in Python using recursive features. Here’s a Python code  to calculate the nth Fibonacci number by using recursion:

Def fibonacci(n):
    if n <= 0:
        return 0 
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci (n-2)
#import csv

Iterative Fibonacci Series in Python,

An iterative method to calculate Fibonacci numbers in Python, involves using loops to build the sequence iteratively. 

Iterative Fibonacci Algorithm in Python:

def fibonacci_iterative(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    Else:
        fib_prev = 0  # Initialize the first Fibonacci number
        fib_current = 1  # Initialize the second  Fibonacci number
        For _ in range(2, n + 1):
            fib_next = fib_prev + fib_current  # Calculate the next Fibonacci number
            fib_prev, fib_current = fib_current, fib_next  # Update values for the next iteration 
        return fib_current
#import csv

Comparison with the Recursive Approach

Distinction basis Recursive Approach Iterative Approach
Efficiency This approach is more efficient for large “n” values, calculating the Fibonacci numbers iteratively and without redundant calculations. This approach is less efficient, especially for large “n” as it causes redundant calculations.
Time Complexity 0(n) (Linear) 0 (2^n) (Exponential) 
Space Complexity 0(1) (Constant)  0(n) (Linear) 

Memoization for Efficient Calculation

Memoization is a method that speeds computer programs or algorithms by storing the results of expensive function calls and returning the cached result when the same inputs occur again. It is useful in optimizing the Fibonacci series in Python calculations as the recursive approach recalculates the same Fibonacci numbers many times, leading to inefficiency.

Python Program to generate Fibonacci numbers

def fibonacci(n):
    fib_sequence = [0, 1]
    
    for i in range(2, n):
        next_fib = fib_sequence[-1] + fib_sequence[-2]
        fib_sequence.append(next_fib)
    
    return fib_sequence

# Change the value of 'n' to generate a different number of Fibonacci numbers
n = 10
result = fibonacci(n)

print(f"The first {n} Fibonacci numbers are: {result}")

This program defines a function Fibonacci that generates a Fibonacci sequence up to the specified length n. The sequence is then printed for the first 10 Fibonacci numbers, but you can change the value of n to generate a different number of Fibonacci numbers.

How Memoization Reduces Redundant Calculations

In Fibonacci series calculations in Python, without memoization, the recursive algorithm recalculates the same numbers repeatedly. Memoization addresses this inefficiency by storing the results. When the function is called again with the same input, it utilizes the previously calculated result for the problem, enhancing the efficiency of the Fibonacci series computation.

Implementing Memoization in Python for Fibonacci

Here’s how you implement  memoization in Python to optimize Fibonacci calculations:

# Create a dictionary to store computed Fibonacci numbers.
Fib_cache = {}
def fibonacci_memoization(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1

    # Check if the result is already within the cache.
    If n in fib_cache:
        return fib_cache[n]

    # If not, calculate it recursively and store it in the cache.
    fib_value = fibonacci_memoization(n - 1) + fibonacci_memoization(n - 2)
    fib_cache[n] = fib_value

    return fib_value
#import csv

Dynamic Programming for Python Fibonacci Series

Dynamic programming is a strategy used to solve problems by breaking them down into smaller subproblems and fixing each subproblem only once, storing the results to avoid redundant calculations. This approach is very effective for solving complex problems like calculating Fibonacci numbers successfully.

Explanation of the Dynamic Programming Approach to Fibonacci:

Dynamic programming involves storing Fibonacci series in Python numbers in an array or dictionary when they’re calculated so that they can be reused whenever needed. Instead of recalculating the same Fibonacci numbers, dynamic programming stores them once and retrieves them as needed.

Using an Array or Dictionary to Store Intermediate Results

The dynamic programming approach can be used with either an array or a dictionary (hash table) to store intermediate Fibonacci numbers. 

def fibonacci_dynamic_programming(n):
    fib = [0] * (n + 1)  # Initialize an array to store Fibonacci numbers.
    Fib[1] = 1  # Set the base cases.
    
    For i in range(2, n + 1):
        fib[i] = fib[i - 1] + fib[i - 2]  # Calculate and store the Fibonacci numbers.
    Return fib[n]  # Return the nth Fibonacci number.
#import csv

Benefits of Dynamic Programming in Terms of Time Complexity

  • Dynamic Programming for Fibonacci: This method in Python helps generate Fibonacci numbers more efficiently.
  • Reduced Time Complexity: It reduces the time complexity from exponential (O(2^n)) in the naive recursive approach to linear (O(n)).
  • Efficient Reuse: It stores previously calculated values, so it avoids recalculating them. Each Fibonacci number is calculated once and then retrieved when needed.
  • Improved Scalability: This approach works well even for large numbers, making it suitable for real-world applications.

Space Optimization for Fibonacci

Space optimization strategies for calculating Fibonacci numbers aim to reduce memory utilization by storing only the important previous values rather than the entire sequence. These techniques are especially useful when memory efficiency is a concern.

Using Variables to Store Only Necessary Previous Values

One of the most regularly used space-optimized strategies for Fibonacci is to apply variables to store only the two most recent Fibonacci numbers rather than an array to store the complete sequence. 

def fibonacci_space_optimized(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1

    fib_prev = 0  # Initialize the preceding Fibonacci number.
    Fib_current = 1  # Initialize the current Fibonacci number.

    For _ in variety(2, n + 1):
        fib_next = fib_prev + fib_current  #Calculate the next Fibonacci number.
        fib_prev, fib_current = fib_current, fib_next  # Update values for the next iteration.

    Return fib_current  # Return the nth Fibonacci number.

#import csv

Trade-offs Between Space and Time Complexity

Space-optimized techniques for Fibonacci series in python come with trade-offs among space and time complexity:

Space Efficiency: Space-optimized approaches use much less memory because they store only a few variables (generally two) to keep track of the latest Fibonacci numbers. This is relatively space-efficient, making it suitable for memory-constrained environments.

Time Efficiency: While these strategies are not linear (O(n)) in terms of time complexity, they may be slightly slower than dynamic programming with an array because of the variable assignments. However, the difference is normally negligible for practical values of “n”.

Generating Fibonacci Numbers up to N

Generating Fibonacci numbers up to N Python can be done with a loop. Here’s a Python code  that generates Fibonacci numbers up to N:

def generate_fibonacci(restriction):
    if limit <= 0:
        return []

    fibonacci_sequence = [0, 1]  # Initialize with the first two Fibonacci numbers.
    While True:
        next_fib = fibonacci_sequence[-1] + fibonacci_sequence[-2]
        if next_fib > restriction:
            break
        fibonacci_sequence.append(next_fib)
    return fibonacci_sequence
#import csv

Applications of Generating Fibonacci Sequences within a Range

  • Number Series Analysis: Generating Fibonacci numbers within a limit can be useful for analyzing and studying number sequences, identifying patterns, and exploring mathematical properties.
  • Performance Analysis: In computer science and algorithm evaluation, Fibonacci sequences can be used to analyze the performance of algorithms and data structure, mainly in terms of time and space complexity.
  • Application Testing: In application testing, Fibonacci numbers may be used to create test cases with varying input sizes to assess the performance and robustness of software applications.
  • Financial Modeling: Fibonacci sequences have applications in financial modeling, specifically in studying market trends and price movements in fields like stock trading and investment analysis.

Fibonacci Series Applications

Applications of Fibonacci :

  • In Nature: The Fibonacci sequence appears in the way leaves, petals, and seeds are arranged in plants, helping them grow efficiently.
  • Golden Ratio: This comes from the Fibonacci sequence and is used in design and art to create balanced and nice-looking patterns.
  • In Technology: Fibonacci numbers make algorithms better, helping solve problems faster, like in Python programming.
  • In Finance: It’s also used to study the market and predict price movements.
  • Why It’s Important: The Fibonacci sequence is useful in many areas like nature, art, and technology, showing its importance in different fields.

Fibonacci in Trading and Finance

Here are some points of Fibonacci in Finance and Trading:

  • Fibonacci is used in trading to find important price levels.
  • It helps spot where prices might stop falling or rising.
  • It predicts when prices might change direction or keep going.
  • Traders use it along with other tools to make better decisions.
  • They also look for patterns like the Golden Ratio to guess price movements.

Conclusion

While seemingly rooted in mathematics, the Fibonacci series in Python also has relevance in data science. Understanding the principles of sequence generation and pattern recognition inherent in the Fibonacci series can aid data scientists in recognizing and analyzing recurring patterns within datasets, a fundamental aspect of data analysis and predictive modeling in data science.. Enroll in our free Python course to advance your python skills.

Q1. What is Python Fibonacci series?

A. Python Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. It’s a common algorithmic problem used to demonstrate recursion and dynamic programming concepts in Python.

Q2. What is the formula of the Fibonacci Series?

A.  F(n) = F(n-1) + F(n-2)

Q3. What is the equation for the Fibonacci sequence in Python?

A. A. The equation for the Fibonacci sequence in Python can be implemented using recursion or iteration. One common recursive implementation is:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

Q4. How to code a Fibonacci sequence in Python while loop?

A. Use this code to generate fibonacci :
a, b = 0, 1
n_terms = 10
count = 0
while count < n_terms:
print(a, end=” “)
a, b = b, a + b
count += 1

Analytics Vidhya Content team

Responses From Readers

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details