6

I wrote the following code to generate random numbers in the [0, int.MaxValue) range, but I wasn't sure how to restrict the range to [0, randomMax) while maintaining an even distribution:

private static int GetNextInt32(this RNGCryptoServiceProvider random)
{
  var buffer = new byte[sizeof(int)];
  random.GetBytes(buffer);
  return Math.Abs(BitConverter.ToInt32(buffer, 0));
}

Thanks.

alhazen
  • 1,907
  • 3
  • 22
  • 43

4 Answers4

4

Here's one way to do it: http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=775. See the section titled "Creating a System.Random Replacement."

Note, however, that using the modulus operator might not be the best way to ensure a good distribution. A possibly better way would be (int)(NextDouble() * (MaxValue - 1));

Your code has a latent bug. If buffer contains the hex values 00 00 00 80, which is int.MinValue, Math.Abs will throw an exception.

Note that calling GetBytes on the RNGCryptoServiceProvider is very slow compared to calling Random.Next. You're better off calling GetBytes to fill a larger buffer, and then dribble the random numbers from it. My example shows how that's done.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • 1
    Jim, `Next() % maxValue` is biased; as a simple example if `Next()` returns 0, 1, 2 or 3 evenly distributed, `Next() % 3` will return 0 twice as frequently as 1 or 2. – Rawling Apr 02 '13 at 12:54
  • @Rawling: Yes, I did mention that using the modulus operator could be a problem. Thanks for the concrete example. – Jim Mischel Apr 02 '13 at 15:04
  • Apologies, I hadn't seen your caveat there. – Rawling Apr 02 '13 at 15:15
3

There's a description of a suitable algorithm in the Java nextInt documentation.

The algorithm repeatedly rejects any values that will cause an uneven distribution and tries again. This means, theoretically, that in the worst-case scenario it could loop forever. In reality it will be pretty quick.

Here's a (completely untested) C# translation:

public static int GetNextInt32(this RNGCryptoServiceProvider rng, int maxValue)
{
    if (maxValue < 1)
        throw new ArgumentOutOfRangeException("maxValue", maxValue, "Value must be positive.");

    var buffer = new byte[4];
    int bits, val;

    if ((maxValue & -maxValue) == maxValue)  // is maxValue an exact power of 2
    {
        rng.GetBytes(buffer);
        bits = BitConverter.ToInt32(buffer, 0);
        return bits & (maxValue - 1);
    }

    do
    {
        rng.GetBytes(buffer);
        bits = BitConverter.ToInt32(buffer, 0) & 0x7FFFFFFF;
        val = bits % maxValue;
    } while (bits - val + (maxValue - 1) < 0);

    return val;
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
2

An MSDN magazine article shows you how to create a Random that uses the cryptographic RNG:

http://msdn.microsoft.com/en-us/magazine/cc163367.aspx

(The article is no longer directly accessible. It was from the September 2007 issue, the title was "Tales from the CryptoRandom". You'll have to download the archived issue. It's .chm so you'll have to unblock it as being from the internet, before you can read it. You could also use the internet archive.)

Mark Sowul
  • 10,244
  • 1
  • 45
  • 51
  • 1
    Right now, the link above redirects to https://learn.microsoft.com/en-us/archive/msdn-magazine/2007/september/net-matters-tales-from-the-cryptorandom which is the correct article. – Patrick McDonald Sep 30 '21 at 13:59
0

If you don't need much speed, maybe you can try this:

    private static RNGCryptoServiceProvider _RNG = new RNGCryptoServiceProvider();  

    private static int GetNextRnd (int min, int max)
    {
        byte[] rndBytes = new byte[4];
        _RNG.GetBytes(rndBytes);
        int rand = BitConverter.ToInt32(rndBytes, 0); 
        const Decimal OldRange = (Decimal)int.MaxValue - (Decimal)int.MinValue;
        Decimal NewRange = max - min;
        Decimal NewValue = ((Decimal)rand - (Decimal)int.MinValue) / OldRange * NewRange + (Decimal)min;
        return (int)NewValue;
    }

This will scale the full-range int number to your range of values, mantaining the distribution.

I know it's an old post, but I've run to a similar problem and this soultion worked for me.

Adam Calvet Bohl
  • 1,009
  • 14
  • 29