Wanted: Gaussian Random Number Generator
Karl Heuer
karl at haddock.ima.isc.com
Mon Sep 25 10:35:49 AEST 1989
In article <927 at skye.ed.ac.uk> ken at aiai.UUCP (Ken Johnson) writes:
>>[wants random numbers with Gaussian distribution]
>[includes code to sum 12 uniform-distribution random numbers]
First, the standard rand() function is uniform on a range of *integers*, so
you'd have to replace rand() with rand()/(RAND_MAX+1.0) to get what you want.
Second, the resulting distribution is just an approximation, not a true
Gaussian distribution. (All its values are in the range [-6,6], whereas a
true Gaussian goes all the way to infinity.) It may be close enough for your
application, but you should be aware of the differences.
Third, a benchmark once revealed that it can be *slower* than the (already
posted) mathematically exact Gaussian that you can get from two uniform
variables and sin/cos/log. (Your results may vary.)
>The 12 is a magic number... If anyone can explain why clearly enough for me
>to understand, I will send them a Beer Token.
It's because 12 is the number in a dozen. For bakery applications, e.g. if
this code is to be used in a toast-flipping simulation of the Murphy's Law
phenomenon, one should use 13. (<-- Culture-dependent joke.)
But seriously, the reason is simply that the uniform distribution on [0,1) has
a variance of exactly 1/12.
Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
More information about the Comp.lang.c
mailing list