Friday, April 29, 2011

Harmonic mean

*Disclaimer*

Mathematics

This post is going to be about another form of average, called the harmonic mean and this is found using the following formula:


It may look a bit complex at first, but really, it's not.

Say we want to find the arithmetic mean of the the following numbers 5, 2, 4, 10. Let's start by taking care of the denominator of the formula first:


As you now know, that's a summation over the reciprocals of our numbers:


We're not ready yet though because that's only half of the formula. So, now we ended up with this complex fraction:


Now we simplify that complex fraction by multiplying the numerator by the reciprocal of the denominator:


Therefore we can say that 'the harmonic mean is the reciprocal of the arithmetic mean of the reciprocals' [Wikipedia].

Programming

Now let's write our harmonic mean function in JavaScript:

var harmonic = function (numbers) {
  var length = numbers.length, denominator = 0, i = 0;
  
  for (; i < length; ++i) {
    denominator += 1 / +numbers[i]; 
  }
  
  return length / denominator;
};

harmonic([5,2,4,10]); // 3.8095238095238093

No comments:

Post a Comment