Skip to content

Instantly share code, notes, and snippets.

Created August 27, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1fb54c43107a71e69cfedf84aded23d6 to your computer and use it in GitHub Desktop.
Save anonymous/1fb54c43107a71e69cfedf84aded23d6 to your computer and use it in GitHub Desktop.
nate central limit theorem demo
license: mit
<!DOCTYPE html>
<head>
<!-- trying to demo what they did here with Java: http://onlinestatbook.com/2/sampling_distributions/clt_demo.html Except without Java -->
<meta charset="utf-8"><!-- Load c3.css -->
<link href="http://c3js.org/css/c3-b03125fa.css" rel="stylesheet" type="text/css">
<!-- Load d3.js and c3.js -->
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="http://c3js.org/js/c3.min-4c5bef8f.js"></script>
<script src="https://d3js.org/d3-random.v1.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
</head>
<body>
<div id="chart"><div>
<script>
function getRandomSubarray(arr, size) {
var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
//histogram
var t = 90; //number of thresholds
//population
var r = 100000; //population size; passed to range func
var distribution = 'randomLogNormal';
var mu = 0;
var sigma = 0.5;
//sampling distribution
var sample_size = 5;
var num_samples = 1000;
function getRandomSubarray(arr, size) {
/* http://stackoverflow.com/a/11935263/1175496 */
var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
function sample_dist(sample_size, num_samples, pop) {
return d3
.range(num_samples)
.map(function(){
return avg(getRandomSubarray(pop, sample_size));
})
}
function avg(nums) {
return nums
.reduce(function(a,b) {
return a+b })/nums.length
}
function sample_dist(s_size, num_samples, pop) {
return d3
.range(num_samples)
.map(function(){
//pointing at global variables;
return avg(getRandomSubarray(pop, s_size)); })
}
var pop=d3.range(r).map(d3[distribution](mu, sigma));
var pop_dist = d3.histogram().thresholds(40)(pop).map(function(d){return d.length});
var s_dist = d3.histogram().thresholds(40)(sample_dist(5,1000,pop)).map(function(d){return d.length});
var chart = c3.generate({
data: {
columns: [
['data1'].concat(pop_dist),
//['data2', 130, 100, 140, 200, 150, 50]
],
type: 'bar'
},
bar: {
width: {
ratio: 0.90 // this makes bar width 50% of length between ticks
}
// or
//width: 100 // this makes bar width 100px
}
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment