ga-dc / wdi5

wdi dc 5
10 stars 34 forks source link

JS Coding Challenge #43

Closed nhashmi closed 9 years ago

nhashmi commented 9 years ago

// JavaScript Coding Challenge

// Challenge: Return the standard deviation of a set of numbers

var standardDeviation = function(){
  sum = 0;
  for (var i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  };

  // Get the mean
  var meanArguments = parseFloat(sum) / parseFloat(arguments.length);

  // For each number, subtract the mean from it and square that difference
  var sumOfSquares = 0;
  for (var i = 0; i < arguments.length; i++) {
    var residual = (arguments[i] - meanArguments) * (arguments[i] - meanArguments);
    sumOfSquares += residual;
  };

  // Get the mean of those squared differences
  var meanSquares = parseFloat(sumOfSquares) / parseFloat(arguments.length);

  // Get the square root of that mean
  var result = Math.sqrt(meanSquares);

  return result;
}

console.log("The standard deviation of (3, 4, 5, 6, and 7) is " + standardDeviation(3, 4, 5, 6, 7));

console.log("The standard deviation of (3, 6, 9, 12) is " + standardDeviation(3, 6, 9, 12));