Skip to content

Instantly share code, notes, and snippets.

@toboid
Last active September 2, 2017 16:23
Show Gist options
  • Select an option

  • Save toboid/faf18e09e1287217cf12d9a4c0fe3731 to your computer and use it in GitHub Desktop.

Select an option

Save toboid/faf18e09e1287217cf12d9a4c0fe3731 to your computer and use it in GitHub Desktop.
Calculating variance and standard deviation
const orderCounts = [3, 34, 15, 55, 6, 7];
const mean = sample => sample.reduce((sum, x) => sum + x, 0) / sample.length;
const square = x => x * x;
const difference = x => y => x - y;
const variance = sample => mean(sample.map(difference(mean(sample))).map(square));
// Variance
const σ2 = variance(orderCounts);
// Standard deviation
const σ = Math.sqrt(σ2);
// One way identify outliers, each have their own trade-offs
const outliers = orderCounts.filter((orderCount) => Math.abs(mean(orderCounts) - orderCount) > σ);
console.log('Variance', σ2);
console.log('Standard Deviation', σ);
console.log('Outliers', outliers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment