Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Last active April 15, 2020 14:27
Show Gist options
  • Save mxriverlynn/b7c6615ecf1fe9ad60a8 to your computer and use it in GitHub Desktop.
Save mxriverlynn/b7c6615ecf1fe9ad60a8 to your computer and use it in GitHub Desktop.
Standard deviation, in JavaScript
var sum = values.reduce(function(sum, value){
return sum + value;
}, 0);
var avg = sum / data.length;
var diffs = values.map(function(value){
var diff = value - avg;
return diff;
});
var squareDiffs = values.map(function(value){
var diff = value - avg;
var sqr = diff * diff;
return sqr;
});
function average(data){
var sum = data.reduce(function(sum, value){
return sum + value;
}, 0);
var avg = sum / data.length;
return avg;
}
var avgSquareDiff = average(squareDiffs);
var stdDev = Math.sqrt(avgSquareDiff);
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;
}
@rubenlg
Copy link

rubenlg commented Dec 12, 2019

This doesn't compute standard deviation, it computes the uncorrected standard deviation, because it uses 1/N. The denominator for stdev should be N-1, not N. The squared differences should not be averaged.

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