How to calculate the harmonic mean

The harmonic mean is another kind of average value for a discrete data set. To calculate the harmonic mean of a set of N data values we need to divide the number of data values N to the sum of inverses of each data value.

In mathematics there is no particular notation for the harmonic mean. For our example we are going to use:

\[x_{HM}=\frac {N}{{\frac {1}{x_{1}}}+{\frac {1}{x_{2}}}+\cdots +{\frac {1}{x_{N}}}}\]

The general mathematic formula for the harmonic mean is:

\[x_{HM}=\frac {N}{\sum \limits _{i=1}^{N}{\frac {1}{x_{i}}}}\]

We can also write the mathematical expression of the harmonic mean using rational exponents:

\[x_{HM}=\left(\frac {\sum \limits _{i=1}^{N}x_{i}^{-1}}{N}\right)^{-1}\]

Example: Calculate the harmonic mean (average) of the monthly minimum temperature for the given set of data.

MonthMinimum temperature [°C]
January2
February4
March8
April13
May16
June21
July23
August22
September20
October17
November13
December6

We are given 12 measurements of the temperatures, the minimum value for each month. The minimum average temperature for the whole year is the harmonic mean of the data set:

\[x_{HM}=\frac {12}{\frac {1}{2}+\frac {1}{4}+\frac {1}{8}+\frac {1}{13}+\frac {1}{16}+\frac {1}{21}+\frac {1}{23}+\frac {1}{22}+\frac {1}{20}+\frac {1}{17}+\frac {1}{13}+\frac {1}{6}}=7.981970\]

For a better understanding of the result we are going to plot:

  • each monthly minimum temperature as a bar plot
  • the harmonic mean (yearly minimum average temperature) as a line
Monthly minimum temperature and yearly average (harmonic mean)

Image: Monthly minimum temperature and yearly average (harmonic mean)

As a programming exercise, we’ll write a Scilab script which calculates the harmonic mean for the same set of data:

data_N = [2 4 8 13 16 21 23 22 20 17 13 6];
length_N = length(data_N);
sum_inv_N = 0;

for i=1:length_N
 sum_inv_N = sum_inv_N + 1/data_N(i); 
end

x_HM = length_N/sum_inv_N;
mprintf("The harmonic mean is: %f", x_HM);

For further practicing we are going to write down a C script which calculates the harmonic mean for the same set of data (temperatures):

#include<stdio.h>
#include<math.h>

int main(void)
{
 double data_N[12] = {2,4,8,13,16,21,23,22,20,17,13,6};
 int i;
 double sum_inv_N = 0;
 double x_HM = 0;
 double length_N = 12;

for (i=0;i<length_N;i++){
 sum_inv_N = sum_inv_N + 1/data_N[i];
 }

x_HM = length_N / sum_inv_N;
 printf("The harmonic mean is %f: \n",x_HM);

return 0;

}

For any questions or observations regarding this tutorial please use the comment form below.

Don’t forget to Like, Share and Subscribe!

Leave a Reply

Ad Blocker Detected

Dear user, Our website provides free and high quality content by displaying ads to our visitors. Please support us by disabling your Ad blocker for our site. Thank you!

Refresh