|
| 1 | +""" |
| 2 | +The Geometric Mean of n numbers is defined as the n-th root of the product |
| 3 | +of those numbers. It is used to measure the central tendency of the numbers. |
| 4 | +https://en.wikipedia.org/wiki/Geometric_mean |
| 5 | +""" |
| 6 | + |
| 7 | + |
| 8 | +def 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 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + from doctest import testmod |
| 53 | + |
| 54 | + testmod(name="compute_geometric_mean") |
| 55 | + print(compute_geometric_mean(-3, -27)) |
0 commit comments