Python Project: Fibonacci Series Calculation
In this article, I will show a simple Python project that calculates the Fibonacci sequence using two different methods: Recursion and Iteration
Table of contents
- Introduction:
- These are the steps I took to grasp the concepts:
- These are the problems that I encountered:
- This is how I solved those problems:
- 1. Handling Negative Inputs:
- 2. The Recursive Method is Slower Compared to the Iterative Method for Large Numbers:
- 3. Starting initial_time too early increases the recorded execution time:
- Output when running in the terminal:
- Resources:
Introduction:
The Fibonacci sequence is a classic problem that is often used to demonstrate different approaches to solving problems, such as recursion and iteration. The aim of this program is to calculate the nth Fibonacci number, where the sequence starts with 0 and 1. The nth Fibonacci number is the sum of the two preceding ones.
These are the steps I took to grasp the concepts:
Understanding Fibonacci: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1.
Example: 0, 1, 1, 2, 3, 5, 8, 13, ...Recursion Method: I defined the
FiboRecursion(num)
function, which calculates Fibonacci numbers using recursion. It works by repeatedly calling itself with smaller numbers until it reaches the two base cases0
and1
.Iteration Method: I also defined the
FiboIteration(num)
function, which calculates Fibonacci numbers using a loop. It starts with0
and1
and uses a simple loop to add the two previous numbers to get the next one in the sequence.Timing Execution: I used
time.time()
to measure how long each method takes to execute. This helped me compare the performance of both approaches.Below is the complete Python code :
These are the problems that I encountered:
Handling Negative Inputs
The Recursive Method is Slower Compared to the Iterative Method for Large Numbers
Starting
initial_time
too early increases the recorded execution time.
This is how I solved those problems:
1. Handling Negative Inputs:
Problem: Negative numbers are not valid inputs for Fibonacci calculations since the Fibonacci sequence is only defined for non-negative integers. Since the Fibonacci sequence is not defined for negative integers, I wanted to prompt the user to enter a valid, non-negative number instead of letting the program to crash.
Solution: It is better to use a while loop which keeps asking the user for input until a valid non-negative integer is entered. This ensures that the program continues only with a valid input.
# Handling negative input with a loop
import time
while True:
n = int(input("Enter your Number: "))
if n < 0:
print("Please enter a non-negative integer")
else:
initial_time = time.time()
print(f"Using Iteration Method value of Fibonacci({n}) is: {FiboIteration(n)}")
print(f"It took {time.time() - initial_time} seconds using Iteration Method")
print(f"Using Recursion Method value of Fibonacci({n}) is: {FiboRecursion(n)}")
print(f"It took {time.time() - initial_time} seconds using Recursion Method")
break
2. The Recursive Method is Slower Compared to the Iterative Method for Large Numbers:
Problem: The recursive method is slow compared to the iterative method for large numbers because it repeatedly recalculates the Fibonacci numbers for the same values. For example, to compute Fibo(35)
, it calculates Fibo(34)
and Fibo(33)
multiple times, causing redundant calculations and slowing down the program.
FiboRecursion(35) calls FiboRecursion(34) and FiboRecursion(33),
which again call FiboRecursion(33), FiboRecursion(32), and so on.
Solution: Use an iterative approach to avoid this problem by simply looping through the sequence and calculating each Fibonacci number once. This makes it more efficient and faster.
import time
def FiboIteration (num):
previous_num = 0
current_num = 1
for i in range (1, num):
previous_to_previous_num = previous_num
previous_num = current_num
current_num = previous_num + previous_to_previous_num
return current_num
while True:
n = int(input("Enter your Number: "))
if n < 0:
print("Please enter a non-negative integer")
else:
initial_time = time.time()
print(f"Using Iteration Method value of Fibonacci({n}) is: {FiboIteration(n)}")
print(f"It took {time.time() - initial_time} seconds using Iteration Method")
break
3. Starting initial_time
too early increases the recorded execution time:
Problem: When I placed initial_time
at the very start of the program (before any actual calculations), it includes the time spent waiting for user input or other operations. This can result in an inflated recorded execution time.
# Incorrect timing method
import time
initial_time = time.time() # Incorrect Placement
while True:
n = int(input("Enter your Number: "))
if n < 0:
print("Please enter a non-negative integer")
else:
print(f"Using Iteration Method value of Fibonacci({n}) is {FiboIteration(n)}")
print(f"It took {time.time() - initial_time} seconds using Iteration Method")
print(f"Using Recursion Method value of Fibonacci({n}) is {FiboRecursion(n)}")
print(f"It took {time.time() - initial_time} seconds using Recursion Method")
break
Solution: So it’s better to set initial_time
just before the actual calculation starts. This will measure the execution time accurately for the Fibonacci function rather than the entire program.
# Correct timing method
import time
while True:
n = int(input("Enter your Number: "))
if n < 0:
print("Please enter a non-negative integer")
else:
initial_time = time.time() # Set time just before calculation
print(f"Using Iteration Method value of Fibonacci({n}) is {FiboIteration(n)}")
print(f"It took {time.time() - initial_time} seconds using Iteration Method")
print(f"Using Recursion Method value of Fibonacci({n}) is {FiboRecursion(n)}")
print(f"It took {time.time() - initial_time} seconds using Recursion Method")
break
Output when running in the terminal:
Example 1: Invalid Input
Enter your Number: -25
Please enter a non-negative integer
Enter your Number: -45
Please enter a non-negative integer
Enter your Number: -35
Please enter a non-negative integer
Example 2: Valid Input
Enter your Number: 9
Using Iteration Method value of Fibonacci(9) is: 34
It took 0.00042247772216796875 seconds using Iteration Method
Using Recursion Method value of Fibonacci(9) is: 34
It took 0.0010762214660644531 seconds using Recursion Method
Example 3: Iteration Time vs Recursion Time
Enter your Number: 35
Using Iteration Method value of Fibonacci(35) is 9227465
It took 0.0004031658172607422 seconds using Iteration Method
Using Recursion Method value of Fibonacci(35) is 9227465
It took 3.1653623580932617 seconds using Recursion Method
Resources:
My GitHub Repository with project code - Link