randomNormal

Benchmark created on


Description

These create normally distributed random variables with a mean of zero and variance of 1. Such variables are often needed for statistical simulations. For the BellKnop and independent polar algorithms see http://en.wikipedia.org/wiki/Box-Muller_transform

Preparation HTML

<script>
  function bellKnop(){
   var x=2,y=2,s=null,result=null;
   while( (x*x+y*y) > 1.0 ){ 
      x = -1.0+2.0*Math.random();
      y = -1.0+2.0*Math.random();
   }
   s = x*x + y*y ; 
   result = x * Math.sqrt(-2.0*Math.log(s)/s);
   return result; 
  }
  
  var bCache = null;
  
  function bellKnopCached(){
   var x=2,y=2,s=null,common,result=null;
   if (bCache !== null){ result = bCache; bCache=null; return result; }
   while( (x*x+y*y) > 1.0 ){ 
      x = -1.0+2.0*Math.random();
      y = -1.0+2.0*Math.random();
   }
   s = x*x + y*y ; 
   common = Math.sqrt(-2.0*Math.log(s)/s); 
   bCache = y * common;
   result = x * common;
   return result; 
  }
  
  function indepPolar(){
   var u1=Math.random(),u2=Math.random();
   var result = Math.sqrt(0.0- 2.0*Math.log(u1))*Math.cos(2.0*Math.PI*u2);
   return result;
  }
  
  var pCache = null;
  
  function indepPolarCached(){
   var u1,u2,result,r,u1,u2,a;
   if (pCache !== null){ result = pCache; pCache=null; return result; }
   u1 = Math.random();
   u2 = Math.random();
   r = Math.sqrt( -2.0*Math.log(u1) );
   a = 2.0 * Math.PI * u2;
   pCache = r*Math.cos(a);
   result = r*Math.sin(a);
   return result;
  }
  
  
   
  
  
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
bellKnop
bellKnop();
ready
indepPolar
indepPolar();
ready
indepPolarCached
indepPolarCached();
ready
bellKnopCached
bellKnopCached();
ready

Revisions

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