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

Function geometric_series

maths/series/geometric_series.py:15–60  ·  view source on GitHub ↗

Pure Python implementation of Geometric Series algorithm :param nth_term: The last term (nth term of Geometric Series) :param start_term_a : The first term of Geometric Series :param common_ratio_r : The common ratio between all the terms :return: The Geometric Series starting

(
    nth_term: float,
    start_term_a: float,
    common_ratio_r: float,
)

Source from the content-addressed store, hash-verified

13
14
15def geometric_series(
16 nth_term: float,
17 start_term_a: float,
18 common_ratio_r: float,
19) -> list[float]:
20 """
21 Pure Python implementation of Geometric Series algorithm
22
23 :param nth_term: The last term (nth term of Geometric Series)
24 :param start_term_a : The first term of Geometric Series
25 :param common_ratio_r : The common ratio between all the terms
26 :return: The Geometric Series starting from first term a and multiple of common
27 ration with first term with increase in power till last term (nth term)
28 Examples:
29 >>> geometric_series(4, 2, 2)
30 [2, 4.0, 8.0, 16.0]
31 >>> geometric_series(4.0, 2.0, 2.0)
32 [2.0, 4.0, 8.0, 16.0]
33 >>> geometric_series(4.1, 2.1, 2.1)
34 [2.1, 4.41, 9.261000000000001, 19.448100000000004]
35 >>> geometric_series(4, 2, -2)
36 [2, -4.0, 8.0, -16.0]
37 >>> geometric_series(4, -2, 2)
38 [-2, -4.0, -8.0, -16.0]
39 >>> geometric_series(-4, 2, 2)
40 []
41 >>> geometric_series(0, 100, 500)
42 []
43 >>> geometric_series(1, 1, 1)
44 [1]
45 >>> geometric_series(0, 0, 0)
46 []
47 """
48 if not all((nth_term, start_term_a, common_ratio_r)):
49 return []
50 series: list[float] = []
51 power = 1
52 multiple = common_ratio_r
53 for _ in range(int(nth_term)):
54 if not series:
55 series.append(start_term_a)
56 else:
57 power += 1
58 series.append(float(start_term_a * multiple))
59 multiple = pow(float(common_ratio_r), power)
60 return series
61
62
63if __name__ == "__main__":

Callers 1

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected