Apr 272012

Standard Random class works perfectly fine most of time. However, on bigger sample, you will see some non-random tendencies. Much better random source is RandomNumberGenerator.

Unfortunately RandomNumberGenerator does not actually return random numbers. It returns random bytes. It is our duty to change those random bytes to single double value ranging from 0 to 1 (as from NextDouble function).

Idea is to get 4 random bytes and to convert them to unsigned integer (negative numbers are so passé). If that number was to be in 0 to 1 range it would be enough to divide it by UInt32.MaxValue. Since we need result to be less than 1, we have slightly larger divisor:

private RandomNumberGenerator Rnd;

private double GetRandom() {
    if (this.Rnd == null) { this.Rnd = RandomNumberGenerator.Create(); }
    var bytes = new byte[4];
    var number = BitConverter.ToUInt32(bytes, 0);
    return number / (UInt32.MaxValue + 1.0);

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.