Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

harmonic mean in python

The Harmonic Mean function in Python (scipy.stats.hmean) requires that the input be positive numbers.

For example:

from scipy import stats
print stats.hmean([ -50.2 , 100.5 ])

results in:

ValueError: Harmonic mean only defined if all elements greater than zero

I don't mathematically see why this should be the case, except for the rare instance where you would end up dividing by zero. Instead of checking for a divide by zero, hmean() then throws an error upon inputing any positive number, whether a harmonic mean can be found or not.

Am I missing something here in the maths? Or is this really a limitation in SciPy?

How would you go about finding the harmonic mean of a set of numbers which might be positive or negative in python?

like image 983
Zach Avatar asked May 23 '12 02:05

Zach


4 Answers

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!

like image 93
verdesmarald Avatar answered Nov 13 '22 00:11

verdesmarald


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

like image 30
HYRY Avatar answered Nov 13 '22 00:11

HYRY


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.

like image 7
Chetan Sharma Avatar answered Nov 13 '22 01:11

Chetan Sharma


the mathematical definition of harmonic mean itself does not forbid applications to negative numbers (although you may not want to calculate the harmonic mean of +1 and -1), however, it is designed to calculate the mean for quantities like ratios so that it would give equal weight to each data point, while in arithmetic means or such the ratio of extreme data points would acquire much high weight and is thus undesired.

So you either could try to hardcode the definition by yourself like @HYRY suggested, or may have applied the harmonic mean in the wrong context.

like image 2
nye17 Avatar answered Nov 13 '22 02:11

nye17