I recently needed to generate multivariate normal values in a web browser. Since I was unable to find a simple implementation, I wrote the following JavaScript code. This code is not the fastest, and it also makes use of the Math.random() method which I can’t vouch for, but it seems to do a decent job. The first two functions are needed to generate normal values via the Box-Muller method. This implementation uses the basic trig functions of the JavaScript Math object. The third function performs a Cholesky decomposition, which is need to decompose a correlation matrix. Finally, the last function combines these functions to generate iid normals and then transform them to correlated normals.
I’ve found this standard normal random number generator in a number of places, one of which being from one of Paul Wilmott’s books. The idea is that we can use the Central Limit Theorem (CLT) to easily generate values distributed according to a standard normal distribution by using the sum of 12 uniform random variables and subtracting 6. In Excel, the implementation looks like this:
=RAND()+RAND()+RAND()+RAND()+RAND()+RAND()+RAND()+RAND()+RAND()+RAND()+RAND()+RAND()-6
By doing a simple cut-and-paste, we can stick this formula in an Excel cell and go on with our merry way assuming we have generated values from a standard normal distribution. But what is really going on here, and how good does this generator work?
Read the rest of this entry »