Friday, April 29, 2011

Arithmetic mean

*Disclaimer*

Mathematics

Since now you're already familiar with the summation notation, I'm going to start this post with this:


The arithmetic mean is most commonly referred to as just the average, although it's just one of several ways of calculating an average...and it's probably the one you're most familiar with.

Let's say we have these five numbers 14758 and we want to find their arithmetic mean:


Therefore if we use x for our arithmetic mean, we can represent that as:


Programming

Writing a function for calculating the arithmetic mean in JavaScript shouldn't be too difficult:

var average = function (numbers) {
  var sum = 0, i = 0, j = numbers.length;
  
  for (; i < j; ++i) {
    sum += +numbers[i];
  }
  
  return sum / j;
};

average([1,4,7,5,8]); // 5

No comments:

Post a Comment