Random Normal Distribution (v4)

Revision 4 of this benchmark created 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]
    }
    
    function randRatioOfUniforms() {
        var u, v, x, y, q;
        do {
                u = Math.random();
                v = 1.7156 * (Math.random() - 0.5);
                x = u - 0.449871;
                y = Math.abs(v) + 0.386595;
                q = x*x + y*(0.19600*y - 0.25472*x);
        } while (q > 0.27597 && (q > 0.27846 || v*v > -4.0 * Math.log(u)*u*u));
        return [v/u, 0];
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Box-Muller Method
randBoxMuller();
ready
Marsaglia Polar Method
randMarsaglia();
ready
Approximation Method
randApproximation()
ready
Ratio of Uniforms
randRatioOfUniforms()
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