harmonic mean in python

You can just use the Harmonic Mean define equation:

len(a) / np.sum(1.0/a) 

But, wikipedia says that harmonic mean is defined for positive real numbers:

http://en.wikipedia.org/wiki/Harmonic_mean


There is a statistics library if you are using Python >= 3.6:

https://docs.python.org/3/library/statistics.html

You may use its mean method like this. Let's say you have a list of numbers of which you want to find mean:

list = [11, 13, 12, 15, 17]
import statistics as s
s.harmonic_mean(list)

It has other methods too like stdev, variance, mode, mean, median etc which too are useful.


The harmonic mean is only defined for sets of positive real numbers. If you try and compute it for sets with negatives you get all kinds of strange and useless results even if you don't hit div by 0. For example, applying the formula to the set (3, -3, 4) gives a mean of 12!