diff --git a/maths/geometric_mean.py b/maths/geometric_mean.py index 240d519ad398..e3b050570397 100644 --- a/maths/geometric_mean.py +++ b/maths/geometric_mean.py @@ -4,6 +4,8 @@ https://en.wikipedia.org/wiki/Geometric_mean """ +from math import exp, log + def compute_geometric_mean(*args: int) -> float: """ @@ -36,15 +38,19 @@ def compute_geometric_mean(*args: int) -> float: # Frequently they are restricted to being positive. if product < 0 and len(args) % 2 == 0: raise ArithmeticError("Cannot Compute Geometric Mean for these numbers.") - mean = abs(product) ** (1 / len(args)) + try: + mean = abs(product) ** (1 / len(args)) + except OverflowError: + # The integer product may exceed float range even when its root does not. + mean = exp(log(abs(product)) / len(args)) # Since python calculates complex roots for negative products with odd roots. if product < 0: mean = -mean # Since it does floating point arithmetic, it gives 64**(1/3) as 3.99999996 - possible_mean = float(round(mean)) + possible_mean = round(mean) # To check if the rounded number is actually the mean. if possible_mean ** len(args) == product: - mean = possible_mean + mean = float(possible_mean) return mean