Normal Random Number Generators

Benchmark created by Jasper on


Description

Test speed of Box-Muller method vs just adding three random numbers (a la central limit theorem).

Ideas from: http://www.protonfish.com/random.shtml

JSFiddle statistics: http://jsfiddle.net/wellcaffeinated/HRs7r/

Preparation HTML

<script>
function rnd_bmt() {
    var x = 0, y = 0, rds, c;

    // Get two random numbers from -1 to 1.
    // If the radius is zero or greater than 1, throw them out and pick two new ones
    // Rejection sampling throws away about 20% of the pairs.
    do {
    x = Math.random()*2-1;
    y = Math.random()*2-1;
    rds = x*x + y*y;
    }
    while (rds == 0 || rds > 1)

    // This magic is the Box-Muller Transform
    c = Math.sqrt(-2*Math.log(rds)/rds);

    // It always creates a pair of numbers. I'll return them in an array. 
    // This function is quite efficient so don't be afraid to throw one away if you don't need both.
    return [x*c, y*c];
}

function rnd_snd() {
    return (Math.random()*2-1)+(Math.random()*2-1)+(Math.random()*2-1);
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Box Muller
rnd_bmt();
ready
Central Limit method
//box muller gives two naturally... so choose two for good comparison.
rnd_snd();
rnd_snd();
 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Jasper on