Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

harmonic_mean() in Python

  • Last Updated : 29 Sep, 2021

Harmonic Mean (also known as Contrary mean) is one of several kinds of average and in particular one of the Pythagorean means. Usually used in situations when average rates are desired. The harmonic mean is also the reciprocal of the arithmetic mean of the reciprocals of a given set of observations.

For example, harmonic mean of 1, 4 and 4 can be calculated as : 

{\displaystyle \left({\frac {1^{-1}+4^{-1}+4^{-1}}{3}}\right)^{-1}={\frac {3}{{\frac {1}{1}}+{\frac {1}{4}}+{\frac {1}{4}}}}={\frac {3}{1.5}}=2\, }

Harmonic mean can be incorporated in Python3 by using harmonic_mean() function from the statistics module.  

Syntax : harmonic_mean([data-set])
Parameters : 
[data-set]: which is a list or tuple or iterator of real valued numbers.
Returntype : Returns the harmonic_mean of the given set of data.
Errors and Exceptions :
StatisticsError when a empty data-set is passed or if data-set consist of negative values. 
TypeError for dataset of non-numeric type values. 

Note: Harmonic mean is calculated only using positive values in the list, set, or any sequence. 
Code #1 : 


# Python3 code to demonstrate the
# working of harmonic_mean() function
# Import statistics module
import statistics
# list of positive real valued numbers
data = [1, 3, 5, 7, 9]
# using harmonic mean function to calculate
# the harmonic mean of the given data-set
print("Harmonic Mean is % s " % (statistics.harmonic_mean(data)))

Output : 

Harmonic Mean is 2.797513321492007 

Code #2 : 


# Python3 program to demonstrate harmonic_mean()
# function from the statistics module
# Importing the statistics module
from statistics import harmonic_mean
# Importing fractions module as fr
from fractions import Fraction as fr
# tuple of positive integer numbers
data1 = (2, 3, 4, 5, 7, 9, 11)
# tuple of a set of floating-point values
data2 = (2.4, 5.1, 6.7, 8.9)
# tuple of a set of fractional numbers
data3 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3))
# dictionary of a set of values
# Only the keys are taken in
# consideration by harmonic_mean()
data4 = {1: "one", 2: "two", 3: "three"}
# Printing the harmonic mean of above datasets
print("Harmonic Mean of data set 1 is % s"
                 % (harmonic_mean(data1)))
print("Harmonic Mean of data set 2 is % s"
                 % (harmonic_mean(data2)))
print("Harmonic Mean of data set 3 is % s"
                 % (harmonic_mean(data3)))
print("Harmonic Mean of data set 4 is % s"
                % (harmonic_mean(data4)))

Output : 

Harmonic Mean of data set 1 is 4.299197943900386
Harmonic Mean of data set 2 is 4.574783168721765
Harmonic Mean of data set 4 is 55/56
Harmonic Mean of data set 5 is 1.6363636363636365

Code #3 : Demonstrating StatisticsError 


# Python code to demonstrate StatisticsError
# while using harmonic_mean()
# importing statistics module
import statistics
# data-set of numbers containing
# a negative number
dat1 = [1, -1]
# Statistics Error is raised when the
# data-set passed as parameter is
# empty or contain a negative value

Output : 

Traceback (most recent call last):
  File "C:/Users/Souveek/PycharmProjects/", line 12, in 
    print(statistics.harmonic_mean((1, -1)))
  File "C:\Users\Souveek\AppData\Local\Programs\Python\Python36-32\Lib\", line 356, in harmonic_mean
    T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
  File "C:\Users\Souveek\AppData\Local\Programs\Python\Python36-32\Lib\", line 148, in _sum
    for n, d in map(_exact_ratio, values):
  File "C:\Users\Souveek\AppData\Local\Programs\Python\Python36-32\Lib\", line 356, in 
    T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
  File "C:\Users\Souveek\AppData\Local\Programs\Python\Python36-32\Lib\", line 285, in _fail_neg
    raise StatisticsError(errmsg)
statistics.StatisticsError: harmonic mean does not support negative values

Note: Following codes may not run on online IDEs, since the harmonic_mean() function is newly introduced in Python3.6 
Applications : 
Harmonic Mean is one of the many important tools in finance (under statistics). The weighted harmonic mean is the preferable method for averaging multiples, such as the price–earnings ratio (P/E), in which price is in the numerator. It is also used in calculations in places where the arithmetic mean overestimates the required result. 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!