Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Calculating Sum of Geometric Progression | Basic Mathematical Concepts and Definitions
Mathematics for Data Analysis and Modeling

book
Challenge: Calculating Sum of Geometric Progression

In the previous chapter, we discovered a formula to calculate the sum of elements of an arithmetic progression. There is also a formula for the sum of a geometric progression:

Let's discover the following real-life case: consider a scenario where a population of bacteria doubles every hour. The initial population is 100 bacteria. We might want to calculate the total population after a certain number of hours. This scenario can be modeled as a geometric progression, where each term represents the population at a specific hour, and the common ratio r is 2 (since the population doubles each hour).

Task

Swipe to start coding

Calculate the sum of first n elements of geometric progression using both for loop and the formula described above.

  1. Specify the arguments of the formula.
  2. Specify parameters of for loop.

Once you've completed this task, click the button below the code to check your solution.

Solution

def sum_geometric_progression_formula(a, r, n):

sum_formula = a * (1 - r**n) / (1 - r)
return sum_formula

def sum_geometric_progression_loop(a, r, n):

progression_sum = 0
current_term = a
for _ in range(n):
progression_sum += current_term
current_term *= r
return progression_sum

# Example usage
a = 100 # First term
r = 2 # Common ratio
n = 5 # Number of terms in the geometric progression

# Calculate the sum using the formula
sum_formula = sum_geometric_progression_formula(a, r, n)
print(f'Sum using formula is {sum_formula}')

# Calculate the sum using a loop
sum_loop = sum_geometric_progression_loop(a, r, n)
print(f'Sum using loop is {sum_loop}')

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 4
# Function that calculates the sum using formula
def sum_geometric_progression_formula(a, r, n):
sum_formula = a * (1 - r**___) / (1 - ___)
return sum_formula

# Function that calculates the sum using loop
def sum_geometric_progression_loop(a, r, n):

progression_sum = 0
current_term = a
for i in range(n):
progression_sum ___ current_term
current_term ___ r
return progression_sum

# Example usage
a = 100 # First term
r = 2 # Common ratio
n = 5 # Number of terms in the geometric progression

# Calculate the sum using the formula
sum_formula = sum_geometric_progression_formula(a, r, n)
print(f'Sum using formula is {sum_formula}')

# Calculate the sum using a loop
sum_loop = sum_geometric_progression_loop(a, r, n)
print(f'Sum using loop is {sum_loop}')
toggle bottom row
some-alt