Normally distributed random

An approximation of normal distribution based on the central limit theorem.

by Göran Andersson

HTML

<div id="container"></div>

CSS

#container {
    position: relative;
    width: 400px;
    height: 500px;
    border: 1px solid #000;
}
#container div {
    position: absolute;
    bottom: 0;
    width: 2px;
}

JavaScript

// n = 2 doesn't produce a bell curve
function rnd() {
    return Math.random() - Math.random();
}

// n = 6 gives a good enough approximation
function rnd2() {
    return ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3;
}

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.round(100 * f())]++;
    }
    for (var i = 0; i < 200; i++) {
        $('#container').append($('<div>').css({
            left: i * 2 + 'px',
            height: numbers[i] / 25 + 'px',
            background: color
        }));
    }
}

draw(rnd, 700000, 'rgba(128,0,0,.4)');
draw(rnd2, 600000, 'rgba(0,128,0,.6)');