Waivio

The Harmonic Mean With Python & R Code

6 comments

dkmathstats6 years agoHive.Blog3 min read

The Harmonic Mean


Hi there. In this math post, I talk about the harmonic mean. The harmonic mean is an average like the usual arithmetic mean but this harmonic mean is not as well known.

This harmonic mean does have finance applications as shown by this Investopedia page.

Math text rendered from QuickLaTeX.com.


 

Contents List


  • Definition Of Harmonic Mean
  • An Example
  • Python Programming Code Of Harmonic Mean
  • R Programming Code

Definition Of Harmonic Mean


Given a set/list of numbers the harmonic mean is the amount of numbers divided by the sum of each reciprocal of numbers.

In general math notation, given a list of

the harmonic mean formula looks like this:

 

 

Note that n is how many numbers in the list of numbers. In addition, the reciprocal of a number j is 1 divided by j.

This harmonic mean is different from the usual arithmetic mean and is different from the geometric mean. In the usual arithmetic mean for averages, we add all the numbers and divide by how many numbers there are. With the geometric mean, we multiply all the numbers together and take the n-th root of this product.


 

An Example


For this example, we have a list of five numbers. These five numbers (n = 5) are 1, 4, 10, 5 and 2. The calculations for the harmonic mean would be as follows:

 


 

Python Code Of Harmonic Mean


Here is some supplementary Python code for obtaining the harmonic mean. It is not too difficult with the use of the Numpy library. The code should be self explanatory.

 

# Harmonic Mean In Python

import numpy as np

 

numbers_list = np.array([1, 4, 10, 5, 2])

# Take reciprocal (element-wise)

1 / numbers_list

array([1.  , 0.25, 0.1 , 0.2 , 0.5 ])

 

# Harmonic mean: 5 divided by the sum of reciprocals

len(numbers_list) / sum(1 /  numbers_list)

2.439024390243903

 

The Harmonic Mean As A Python Function

# Define Harmonic mean function:
def harmonic_mean(num_list, precision = 2):
    return round(len(num_list) / np.sum(1 / np.array(num_list)), precision)


harmonic_mean(numbers_list, precision = 5)
2.43902

 


 

R Programming Code


The harmonic mean in R requires a little bit less typing compared to Python. Defining a function in R is different compared to Python.

# Create vector of numbers
numbers <- c(1, 4, 10, 5, 2)

# Harmonic mean: 5 divided by sum of reciprocals:

length(numbers) / (sum(1/numbers))

2.439024

 

Harmonic Mean Function In R


harmonic_mean <- function(num_list, precision = 2) {
  return(round(length(num_list) / sum(1/num_list), precision))
}


harmonic_mean(numbers, precision = 3)
2.439

 


 

Thank you for reading.

Comments

Sort byBest