mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-04-22 05:37:36 +00:00
sum_of_geometric_progression (#2168)
* Add files via upload * Rename sum_of_Geometric_Progression.py to sum_of_geometric_progression.py * Update sum_of_geometric_progression.py * Update maths/sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update maths/sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update maths/sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update sum_of_geometric_progression.py * Update sum_of_geometric_progression.py * Type hints and test for zeros and negative numbers * Update sum_of_geometric_progression.py Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
05c14c6be8
commit
6c2c08c076
28
maths/sum_of_geometric_progression.py
Normal file
28
maths/sum_of_geometric_progression.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
def sum_of_geometric_progression(
|
||||||
|
first_term: int, common_ratio: int, num_of_terms: int
|
||||||
|
) -> float:
|
||||||
|
""""
|
||||||
|
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
|
||||||
|
>>> sum_of_geometric_progression(1, 2, 0)
|
||||||
|
-0.0
|
||||||
|
>>> sum_of_geometric_progression(-1, 2, 10)
|
||||||
|
-1023.0
|
||||||
|
>>> sum_of_geometric_progression(1, -2, 10)
|
||||||
|
-341.0
|
||||||
|
>>> sum_of_geometric_progression(1, 2, -10)
|
||||||
|
-0.9990234375
|
||||||
|
"""
|
||||||
|
if common_ratio == 1:
|
||||||
|
# Formula for sum if common ratio is 1
|
||||||
|
return num_of_terms * first_term
|
||||||
|
|
||||||
|
# Formula for finding sum of n terms of a GeometricProgression
|
||||||
|
return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms)
|
Loading…
x
Reference in New Issue
Block a user