Saturday, September 29, 2007

Random draws from Gaussian, Logit and Exponential

I implemented some probability distributions in JavaScript. The attached file contains a set of functions for sampling from the standard normal, the logit and the exponential distribution, as well as their density and distribution function. Their quality relies entirely on the uniform distribution sampler of the browsers javascript engine (Math.random()).

The file defines the functions as methods of the Math object, but there is also a new, single instance, Stat object that you might one to use to distinguish the two. The Stat object is merely an alias for the Math object. I used the R/S-plus naming conventions for the functions: psomething codes the distribution function, dsomething the corresponding density, and rsomething generates samples from that distribution. The function rnorm() generates standard normals by rejection sampling (on average about 22 calls to random() for every 10 samples drawn) and are accurate if random() is accurately uniform (I tested it in IE6, Firefox 2, Safari 3, Opera 9: drew 50000 samples and tested for disparity from standard normal using a KS-test, and repeated that a couple of times). The function pnorm however is a crude (logit) approximation that will differ less than 0.01 from the true probability (maximum differences at ±0.574 and ±2.04; greates accuracy at 0, ±1.22, and beyond ±4).

An example of the use of rnorm is:

   <html>
   <head>
     <script type="text/javascript" src="Stat.js"></script>
   </head>
   <body>
     <pre>
     <script>
         for(var i=0; i < 100; i++) 
             document.write(Math.rnorm()+" ");
    </script>
    </pre>
   </body>  
   </html>
The result is

Stat.js

No comments: