Python : easy way to do geometric mean in python?

user6922072 picture user6922072 · Mar 29, 2017 · Viewed 52.4k times · Source

I wonder is there any easy way to do geometric mean using python but without using python package. If there is not, is there any simple package to do geometric mean?

Answer

Willem Van Onsem picture Willem Van Onsem · Mar 29, 2017

The formula of the gemetric mean is:

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 do not have to use numpy for that, but it tends to perform operations on arrays faster than Python. See this answer for why.

In case the chances of overflow are high, you can map the numbers to a log domain first, calculate the sum of these logs, then multiply by 1/n and finally calculate the exponent, like:

import numpy as np

def geo_mean_overflow(iterable):
    return np.exp(np.log(iterable).mean())