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

Function compute_geometric_mean

maths/geometric_mean.py:8–48  ·  view source on GitHub ↗

Return the geometric mean of the argument numbers. >>> compute_geometric_mean(2,8) 4.0 >>> compute_geometric_mean('a', 4) Traceback (most recent call last): ... TypeError: Not a Number >>> compute_geometric_mean(5, 125) 25.0 >>> compute_geometric_mean(1,

(*args: int)

Source from the content-addressed store, hash-verified

6
7
8def compute_geometric_mean(*args: int) -> float:
9 """
10 Return the geometric mean of the argument numbers.
11 >>> compute_geometric_mean(2,8)
12 4.0
13 >>> compute_geometric_mean('a', 4)
14 Traceback (most recent call last):
15 ...
16 TypeError: Not a Number
17 >>> compute_geometric_mean(5, 125)
18 25.0
19 >>> compute_geometric_mean(1, 0)
20 0.0
21 >>> compute_geometric_mean(1, 5, 25, 5)
22 5.0
23 >>> compute_geometric_mean(2, -2)
24 Traceback (most recent call last):
25 ...
26 ArithmeticError: Cannot Compute Geometric Mean for these numbers.
27 >>> compute_geometric_mean(-5, 25, 1)
28 -5.0
29 """
30 product = 1
31 for number in args:
32 if not isinstance(number, int) and not isinstance(number, float):
33 raise TypeError("Not a Number")
34 product *= number
35 # Cannot calculate the even root for negative product.
36 # Frequently they are restricted to being positive.
37 if product < 0 and len(args) % 2 == 0:
38 raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.")
39 mean = abs(product) ** (1 / len(args))
40 # Since python calculates complex roots for negative products with odd roots.
41 if product < 0:
42 mean = -mean
43 # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996
44 possible_mean = float(round(mean))
45 # To check if the rounded number is actually the mean.
46 if possible_mean ** len(args) == product:
47 mean = possible_mean
48 return mean
49
50
51if __name__ == "__main__":

Callers 1

geometric_mean.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected