Skip to content

Instantly share code, notes, and snippets.

@DannyJoris
Created December 10, 2012 03:51
Show Gist options
  • Save DannyJoris/4248293 to your computer and use it in GitHub Desktop.
Save DannyJoris/4248293 to your computer and use it in GitHub Desktop.
Statistics mean / variance
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<style type="text/css">
body {
font: 300 13px "Helvetica Neue", Helvetica;
}
</style>
</head>
<body>
<script type="text/javascript">
var arr = [1, 2, 3, 5, 10, 25];
var arrLength = arr.length;
var total = 0;
var mean;
var varianceTotal = 0;
var biasedVariance = 0;
var unbiasedVariance = 0;
// array
document.write("array: " + arr + "<br>");
// array length
document.write("arrLength: " + arrLength + "<br>");
// total
for (var i = 0; i < arrLength; i++) {
total += arr[i];
}
document.write("total: " + total + "<br>");
// mean
mean = parseFloat(total / arrLength).toFixed(2);
document.write("<strong>mean:</strong> " + mean + "<br>");
// sample variance total
for (var i = 0; i < arrLength; i++) {
var square;
var squareSum;
squareSum = (arr[i] - mean);
square = squareSum * squareSum;
square = parseFloat(square).toFixed(2);
varianceTotal = parseFloat(varianceTotal) + parseFloat(square);
document.write("square " + i + ": " + square + "<br>");
}
varianceTotal = parseFloat(varianceTotal).toFixed(2);
document.write("variance total: " + varianceTotal + "<br>");
// biased variance (population)
biasedVariance = (varianceTotal / arrLength);
biasedVariance = parseFloat(biasedVariance).toFixed(2);
document.write("<strong>biased variance (population):</strong> " + biasedVariance + "<br>");
// unbiased variance (sample)
unbiasedVariance = (varianceTotal / (arrLength - 1));
unbiasedVariance = parseFloat(unbiasedVariance).toFixed(2);
document.write("<strong>unbiased variance (sample):</strong> " + unbiasedVariance + "<br>");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment