MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / sum_of_geometric_progression

Function sum_of_geometric_progression

maths/sum_of_geometric_progression.py:1–28  ·  view source on GitHub ↗

" Return the sum of n terms in a geometric progression. >>> sum_of_geometric_progression(1, 2, 10) 1023.0 >>> sum_of_geometric_progression(1, 10, 5) 11111.0 >>> sum_of_geometric_progression(0, 2, 10) 0.0 >>> sum_of_geometric_progression(1, 0, 10) 1.0

(
    first_term: int, common_ratio: int, num_of_terms: int
)

Source from the content-addressed store, hash-verified

1def sum_of_geometric_progression(
2 first_term: int, common_ratio: int, num_of_terms: int
3) -> float:
4 """ "
5 Return the sum of n terms in a geometric progression.
6 >>> sum_of_geometric_progression(1, 2, 10)
7 1023.0
8 >>> sum_of_geometric_progression(1, 10, 5)
9 11111.0
10 >>> sum_of_geometric_progression(0, 2, 10)
11 0.0
12 >>> sum_of_geometric_progression(1, 0, 10)
13 1.0
14 >>> sum_of_geometric_progression(1, 2, 0)
15 -0.0
16 >>> sum_of_geometric_progression(-1, 2, 10)
17 -1023.0
18 >>> sum_of_geometric_progression(1, -2, 10)
19 -341.0
20 >>> sum_of_geometric_progression(1, 2, -10)
21 -0.9990234375
22 """
23 if common_ratio == 1:
24 # Formula for sum if common ratio is 1
25 return num_of_terms * first_term
26
27 # Formula for finding sum of n terms of a GeometricProgression
28 return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected