1

Does anyone have a good example on how to calculate the Harmonic Mean and Geometric Mean Recursively. Is it possible to use a Tail Recursive function?

Thanks!

0

2 Answers 2

0

You can use 'recursive' definitions:

G(x1,x2,...,xn) = (x1 * G(x2,...,xn)^(n-1))^(1/n)
H(x1,x2,...,xn) = n / ( 1/x1 + (n-1)/H(x2,...,xn) )

This isn't efficient way to calculate means, since exponentiation/multiplication is done n times.

Simple python implementation with lists as input parameter (N):

def G(N):
  if len(N) == 1: return N[0]
  return (N[0] * G(N[1:])**(len(N)-1))**(1/len(N))

def H(N):
  if len(N) == 1: return N[0]
  return len(N) / ( 1/N[0] + (len(N)-1)/H(N[1:]) )
1
  • I think its also possible to calculate a partial harmonic mean. There should be a way to add the results up independently and then sum them at the end. Is there another way rather then logarithms that can simplify division or multiplication?
    – Asher
    May 8, 2013 at 18:39
0

for the geometric mean, I could not use @Ante's method because, in my case, 1) the product would become too small for a float and 2) I couldn't read the full serie at all once but I am discovering values one by one. Therefore I couldn't find a better solution than using the logarithm:

int iCount(0);
float GMeanLog(0);
for (int i=1;i<n;i++)
{
if (iCount > 0)
{
    iGMeanLog = GMeanLog+(log(val[i])-GMeanLog)/iCount;
    iCount++;
}
else
{
    iCount++;
    GMeanLog = log(val[i]);
}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.