Home > Back-end >  Geomean of large numbers with numpy
Geomean of large numbers with numpy

Time:02-02

I want to calculate the geomean of some large numbers. Problem is that the result of the product of large numbers is overflow. Example:

a = array([168116745,168117411,168117729,168118170,168118695,168119286,168119610])
print(a.prod())
print(a.prod()**(1.0/len(a)))

Output

1947451320
21.235703778668626

On the other hand it is possible to use the rule of sqrt(a.b) = sqrt(a).sqrt(b). Therefore, I can write

n = 1.0/len(a)
temp = []
for i in len(a):
    temp.append(i**n)

So, I have the partial numbers and I am able to find the product of temp elements. I am looking for a more efficient and smaller code based on the existing libraries. Any idea for that?

CodePudding user response:

One solution is to use logarithms. Try this:

a = array([168116745,168117411,168117729,168118170,168118695,168119286,168119610])
print('GM =', np.exp(np.average(np.log(a))))

Alternatively, scipy has a dedicated geometric mean function.

  •  Tags:  
  • Related