Python: easy way to do geometric mean in python?
5 answers
Formula for metric mean:
So, you can easily write an algorithm like:
import numpy as np
def geo_mean(iterable):
a = np.array(iterable)
return a.prod()**(1.0/len(a))
You don't need to use numpy for this, but it tends to do array operations faster than Python (since there is less "overhead" when casting)
If the probability of overflow is high, you can first move the numbers to the log area, calculate the sum of those logs, then multiply by 1 / n, and finally calculate the exponent, for example:
import numpy as np
def geo_mean_overflow(iterable):
a = np.log(iterable)
return np.exp(a.sum()/len(a))
+31
source to share
Starting from Python 3.8
, the standard library comes with a function as part of a module : geometric_mean
statistics
from statistics import geometric_mean
geometric_mean([1.0, 0.00001, 10000000000.]) // 46.415888336127786
+3
source to share
Here's an overflow-resistant pure Python version, basically the same as the accepted answer .
import math
def geomean(xs):
return math.exp(math.fsum(math.log(x) for x in xs) / len(xs))
0
source to share