Hey Folks! In this tutorial, we will understand what a Geometric Progression is and how to implement the same in the Python programming language.
Introduction to Geometric Progression (G.P.)
Geometric Series is a succession of elements in which the next item is acquired by multiplying the previous item by the common ratio.
A G.P. Series is a number series in which the common ratio of any successive integers (items) is always the same.
This Sum of the G.P Series is based on a mathematical formula.
Sn = a(rn) / (1- r)
Tn = ar(n-1)
Geometric Progress in Python
Let’s get into the understanding of how geometric progression works in Python. We’ll take a look at two different examples of the same to get a better understanding.
1. Print first n terms of the Geometric Progression
There are a number of steps involved to achieve the n GP terms. The steps are as follows:
Step 1 – Take the input of a ( the first term ), r( the common ratio), and n ( the number of terms )
Step 2 – Take a loop from 1 to n+1 and compute the nth term in every iteration and keep printing the terms.
# 1. Take input of 'a','r' and 'n'
a = int(input("Enter the value of a: "))
r = int(input("Enter the value of r: "))
n = int(input("Enter the value of n: "))
# 2. Loop for n terms
for i in range(1,n+1):
t_n = a * r**(i-1)
print(t_n)
Enter the value of a: 1
Enter the value of r: 2
Enter the value of n: 10
1
2
4
8
16
32
64
128
256
512
2. Get Sum of first n terms in Geometric Progression
There are a number of steps involved to achieve the sum of first n GP terms. The steps are as follows:
Step 1 – Take the input of a (the first term), r(the common ratio), and n (the number of terms)
Step 2 – Use the formula mentioned above to compute the sum of the first ‘n’ terms.
# 1. Take input of 'a','r' and 'n'
a = int(input("Enter the value of a: "))
r = int(input("Enter the value of r: "))
n = int(input("Enter the value of n: "))
if(r>1):
S_n = (a*(r**n))/(r-1)
else:
S_n = (a*(r**n))/(1-r)
print("Sum of n terms: ",S_n)
Enter the value of a: 1
Enter the value of r: 2
Enter the value of n: 5
Sum of n terms: 32.0
Conclusion
Congratulations! You just learned how to implement Geometric Progression in Python. Hope you enjoyed it! 😇
Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:
- Memoization in Python – A Brief Introduction
- Introduction to Anagrams in Python
- Python Wonderwords module – A brief Introduction
Thank you for taking your time out! Hope you learned something new!! 😄