Get a Float From RandomNumberGenerator

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];
this.Rnd.GetBytes(bytes);
var number = BitConverter.ToUInt32(bytes, 0);
return number / (UInt32.MaxValue + 1.0);
}

Leave a Reply

Your email address will not be published. Required fields are marked *