Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions maths/geometric_mean.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
https://en.wikipedia.org/wiki/Geometric_mean
"""

from math import exp, log


def compute_geometric_mean(*args: int) -> float:
"""
Expand Down Expand Up @@ -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


Expand Down