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?
The formula of the gemetric mean is:
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())