Generating normally distributed random numbers.

Jason Lenthe lenthe at
Sun Jan 31 15:06:51 UTC 2010

> I am working on a project where I have the need to generate normally
> distributed random positive integers, preferably unsigned 64 bit (or
> even longer if possible) integers. More specifically, I will need the
> ability to supply the expected value and the standard deviation for the
> desired distribution, so a standard normal distribution will not do.
> Is there anyone out there who knows how to accomplish this? I have no
> idea whatsoever, and for all I know there may already be a function that
> does this in the math library. I'm quite accomplished when it comes to
> math, but strangely I've never programmed computers for it.

You won't any functions to do this in the standard C or C++ libraries
(though you can readily build on rand()/rand_r()) Java has
java.util.Random.nextGaussian().  Boost has normal_distribution.hpp.

If you're going to do it yourself, usually normal deviates are generated
using the polar method
(  If you really
want to read up on this topic see Chapter 3 of Knuth's Art of of
Computer Programming.

The polar method is really designed for floating point numbers since you
need log() but you could always round the values to the nearest integer.
   Getting getting normal deviates bigger than 64 bits could be a real

A generator for a standard normal distribution is readily adapted to any
normal distribution by multiplying by the standard deviation and adding
the mean.


More information about the freebsd-questions mailing list