Python: easy way to do geometric mean in python?

I wonder if there is an easy way to make a geometric value using python, but without using the python package. If it doesn't, is there any simple package for geometric mean?

+15


source to share


5 answers


Formula for metric mean:

geometrical 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


In case anyone is looking for a library implementation here, scipy has a gmean () , arguably faster and numerically more stable than a custom implementation:



>>> from scipy.stats.mstats import gmean
>>> gmean([1.0, 0.00001, 10000000000.])
46.415888336127786

      

+9


source


just do this:

numbers = [1, 3, 5, 7, 10]


print reduce(lambda x, y: x*y, numbers)**(1.0/len(numbers))

      

+3


source


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


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







All Articles