Normally distributed random
An approximation of normal distribution based on the central limit theorem.
HTML
<div id="container"></div>
CSS
#container {
position: relative;
width: 600px;
height: 300px;
border: 1px solid #000;
}
#container div {
position: absolute;
bottom: 0;
width: 3px;
}
JavaScript
function draw(f, cnt, color) {
var numbers = [];
for (var i = 0; i < 200; i++) numbers[i] = 0;
for (var i = 0; i < cnt; i++) {
numbers[100 + Math.max(-100,Math.min(Math.round(100 * f()),100))]++;
}
for (var i = 0; i < 200; i++) {
$('#container').append($('<div>').css({
left: i * 3 + 'px',
height: (numbers[i]/cnt*300*20) + 'px',
background: color
}));
}
}
function rnd() {
return Math.random()
}
// n = 2 doesn't produce a bell curve rather triangle
function rnd1() {
return (Math.random() + Math.random())/2;
}
// n = 6 gives a good enough approximation
function rnd2() {
var n=3;
var s=0;
for(var i=0;i<n;i++) s+=Math.random();
return (s/n);
}
function rnd2a() {
return ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() +Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() ) - 6) / 6;
}
// returns a gaussian random function with the given mean and stdev.
function gaussian(mean, stdev) {
var y2;
var use_last = false;
return function() {
var y1;
if(use_last) {
y1 = y2;
use_last = false;
}
else {
var x1, x2, w;
do {
x1 = 2.0 * Math.random() - 1.0;
x2 = 2.0 * Math.random() - 1.0;
w = x1 * x1 + x2 * x2;
} while( w >= 1.0);
w = Math.sqrt((-2.0 * Math.log(w))/w);
y1 = x1 * w;
y2 = x2 * w;
use_last = true;
}
var retval = mean + stdev * y1;
if(retval > 0)
return retval;
return -retval;
}
}
// make a standard gaussian variable.
var rnd3 = gaussian(1/2, 1/12);
function normal(mu, sigma, nsamples){ //good parameters
if(!nsamples) nsamples = 12
if(!sigma) sigma = 1
if(!mu) mu=0
var run_total = 0
...