harmonic mean in python

后端 未结 4 1302
臣服心动
臣服心动 2021-01-04 01:23

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

For example:

from scipy import st         


        
相关标签:
4条回答
  • 2021-01-04 02:08

    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.

    0 讨论(0)
  • 2021-01-04 02:18

    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

    0 讨论(0)
  • 2021-01-04 02:19

    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!

    0 讨论(0)
  • 2021-01-04 02:21

    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.

    0 讨论(0)
提交回复
热议问题