Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active May 25, 2022 11:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leommoore/ddd8d806a5aa4aef0283 to your computer and use it in GitHub Desktop.
Save leommoore/ddd8d806a5aa4aef0283 to your computer and use it in GitHub Desktop.
Javascript - Calculating Standard Deviations

Javascript - Calculating Standard Deviations

This is based on a excellent post by Derick Bailey.

function standardDeviation(values){
  var avg = average(values);
  
  var squareDiffs = values.map(function(value){
    var diff = value - avg;
    var sqrDiff = diff * diff;
    return sqrDiff;
  });
  
  var avgSquareDiff = average(squareDiffs);
 
  var stdDev = Math.sqrt(avgSquareDiff);
  return stdDev;
}
 
function average(data){
  var sum = data.reduce(function(sum, value){
    return sum + value;
  }, 0);
 
  var avg = sum / data.length;
  return avg;
}

This can then be use like this:

> standardDeviation([1.34,1.78,1.67,0.98,0.56,1.65])

0.4351245032554858
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment