From: "s.wiesen" Subject: Re: random number generator Date: Thu, 15 Feb 2001 10:46:47 +0100 Newsgroups: sci.math.num-analysis Summary: Box-Mueller method to generate normally-distributed random variables Puneet Singla wrote: > Hai, > > I need a random number generator with normal distribution(subj to a certain > mean and variance)......i need a routine in c which would generate this > number.....the random function in c does not take any input on the nature of > the distribution or the moments of the probability distribution > function..........i need something like the "randn" in "matlab".......could > somebody enlighten me on how to do this in "c"?....... > > thanks > Puneet Singla. If you got a uniform random generator (like ran2 (numerical recipes)) it is easy to use the (algebraic) box-mueller method: float v1,v2,s,ar,r1,r2; extern float ran2() do { v1=2.0*ran2()-1.0; v2=2.0*ran2()-1.0; s=v1*v1+v2*v2; } while(s>1.0); ar=log(s) r1=v1*sqrt(-(ar+ar)/s)*sig-mu; r2=v2*sqrt(-(ar+ar)/s)*sig-mu; The advantage of the routine is that it generates two random variables at one time (due to trigonometric reasons) further recommendations: Sheldon.M.Ross, "Simulation", 2nd. ed. or any numerical book bye -- Sven Wiesen Instute for Plasmaphysics, Forschugszentrum Juelich, D-52425 Juelich phone: +49-2461-615075 ============================================================================== From: George Marsaglia Subject: Re: random number generator Date: Thu, 15 Feb 2001 07:11:31 -0500 Newsgroups: sci.math.num-analysis s.wiesen wrote: [partial quote of previous article trimmed --djr] > r1=v1*sqrt(-(ar+ar)/s)*sig-mu; > r2=v2*sqrt(-(ar+ar)/s)*sig-mu; That a pair of normal variates can be represented by means of polar coordinates, x=rho*cos(theta), y=rho*sin(theta) is a result attributed to Box and Meuller, although Gauss attributes it to Laplace. It is the basis of how most of us learned to evaluate int(exp(-.5x^2)) That a uniform point (v1,v2) in the unit circle has the property that s=v1^2+v2^2 is uniform in [0,1) and independent of the point (v1,v2)/sqrt(s) is a result that I used as the basis for a fast and simple way to get a pair of normal points in the plane, (v1,v1)*sqrt(-2*log(s)/s). Although I used this as early as 1956, I thought it too trivial to push for publication. George Marsaglia