Skip to content

Instantly share code, notes, and snippets.

@collimarco
Last active August 29, 2015 14:05
Show Gist options
  • Save collimarco/70cd250a3c505052d3df to your computer and use it in GitHub Desktop.
Save collimarco/70cd250a3c505052d3df to your computer and use it in GitHub Desktop.
V8 Javascript that demonstrates the Central Limit Theorem
// A large number to be used as infinite
var inf = 10000;
// The number of segments in which a continuous random variable is divided
// to get an aproximation in the discrete
var nSegments = 10;
// U ~ Uniform(0, 1)
function u() {
return Math.random();
}
// X ~ Exponential(l)
function x(l) {
return - Math.log(1 - u()) / l;
}
// Take a sample {X1, X2, ... Xn}
function sample(n, distribution, params) {
var s = [];
while (s.length <= n) s.push(distribution.apply(null, params));
return s;
}
// Calculate the frequency of each value in a sample (apply discretization)
function frequency(s) {
var max = Math.max.apply(null, s);
var min = Math.min.apply(null, s);
var segmentSize = (max - min) / nSegments;
var f = [];
var segmentId;
for (var j = 0; j < nSegments; j++) {
f[j] = 0;
}
for (var i = 0; i < s.length; i++) {
segmentId = Math.floor((s[i] - min) / segmentSize);
f[segmentId] += 1;
}
return f;
}
function printSample(s) {
var i, j, out = "";
var f = frequency(s);
for (i = 0; i < f.length; i++) {
out += i + "\t";
for (j = 0; j < f[i]; j++)
out += "+";
out += "\n";
}
print(out);
}
// Y = X1 + X2 + ... Xn => if n -> inf then Y ~ N(0, 1)
function y(n, iid, iidParams) {
var s = sample(n, iid, iidParams);
return s.reduce(function (sum, value) { return sum + value; }, 0);
}
// Main
var xParams = [0.2];
print("X sample");
var xSample1 = sample(100, x, xParams);
printSample(xSample1);
print("Y sample");
var ySample1 = sample(100, y, [inf, x, xParams]);
printSample(ySample1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment