Random Normal Distribution (v2)

Revision 2 of this benchmark created by David Hogg on


Description

Tests to compare performance of various methods to generate random numbers according to a Normal Distribution.

Each of the tested function generate a pair of random numbers. In an actual implementation, the second number would actually be cached to be returned for the next successive call.

To apply mean and standard deviation, apply the following to each returned value r: x = mean + stdDev * r

Setup

function randBoxMuller() {
      var u, v, a, b, x, y;
    
      u = Math.random();
      v = Math.random();
    
      a = Math.sqrt(-2 * Math.log(u));
      b = 2 * Math.PI * v;
    
      x = a * Math.cos(b);
      y = a * Math.sin(b);
    
      return [x, y];
    }
    
    function randMarsaglia() {
      var u, v, s, a, x, y;
      do {
        u = Math.random() * 2 - 1;
        v = Math.random() * 2 - 1;
        s = u * u + v * v;
      } while (s >= 1 || s == 0)
      a = Math.sqrt(-2.0 * Math.log(s) / s);
    
      x = u * a;
      y = v * a;
    
      return [x, y];
    }
    
    function randApproximation() {
      var x, y;
      // this method doesn't actually need to generate a pair of randoms
      // it is doing so in order to compare to the other methods
      x = (Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) / 6;
      y = (Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) / 6;
    
      return [x, y]
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Box-Muller Method
randBoxMuller();
ready
Marsaglia Polar Method
randMarsaglia();
ready
Approximation Method
randApproximation()
ready

Revisions

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

  • Revision 1: published by David Hogg on
  • Revision 2: published by David Hogg on
  • Revision 3: published by David Hogg on
  • Revision 4: published on