Generate random uint

前端 未结 3 662
孤独总比滥情好
孤独总比滥情好 2021-02-18 14:14

I need to generate random numbers with range for byte, ushort, sbyte, short, int, and uint. I am ab

相关标签:
3条回答
  • 2021-02-18 14:46

    José's Daylight Dices

    Or is there an easy way to generate a true random uint?

    I admit, it's not the OQ. It will become clear that there are faster ways to generate random uints which are not true ones. Nevertheless I assume that nobody is too interested in generating those, except when a non-flat distribution is needed for some reason. Let's start with some research to get it easy and fast in C#. Easy and fast often behave like synonyms when I write code.

    First: Some important properties

    See MSDN.

    Random constructors:

    • Random(): Initializes a new instance of the Random class, using a time-dependent default seed value.
    • Random(int seed): Initializes a new instance of the Random class, using the specified seed value.

    To improve performance, create one Random object to generate many random numbers over time, instead of repeatedly creating new Random objects to generate one random number, so:

    private static Random rand = new Random();
    

    Random methods:

    • rand.Next(): Returns a positive random number, greater than or equal to zero, less than int.MaxValue.
    • rand.Next(int max): Returns a positive random number, greater than or equal to zero, less then max, max must be greater than or equal to zero.
    • rand.Next(int min, int max): Returns a positive random number, greater than or equal to min, less then max, max must be greater than or equal to min.

    Homework shows that rand.Next() is about twice as fast as rand.Next(int max).

    Second: A solution.

    Suppose a positive int has only two bits, forget the sign bit, it's zero, rand.Next() returns three different values with equal probability:

    00
    01
    10
    

    For a true random number the lowest bit is zero as often as it is one, same for the highest bit.
    To make it work for the lowest bit use: rand.Next(2)

    Suppose an int has three bits, rand.Next() returns seven different values:

    000
    001
    010
    011
    100
    101
    110
    

    To make it work for the lowest two bits use: rand.Next(4)

    Suppose an int has n bits.
    To make it work for n bits use: rand.Next(1 << n)

    To make it work for a maximum of 30 bits use: rand.Next(1 << 30)
    It's the maximum, 1 << 31 is larger than int.MaxValue.

    Which leads to a way to generate a true random uint:

    private static uint rnd32()
    {
        return (uint)(rand.Next(1 << 30)) << 2 | (uint)(rand.Next(1 << 2));
    }
    

    A quick check: What's the chance to generate zero?

    1 << 2 = 4 = 22, 1 << 30 = 230

    The chance for zero is: 1/22 * 1/230 = 1/232 The total number of uints, including zero: 232
    It's as clear as daylight, no smog alert, isn't it?

    Finally: A misleading idea.

    Is it possible to do it faster using rand.Next()

                                int.Maxvalue is:    (2^31)-1
       The largest value rand.Next() returns is:    (2^31)-2 
                               uint.MaxValue is:    (2^32)-1
    

    When rand.Next() is used twice and the results are added, the largest possible value is:

    2*((2^31)-2) = (2^32)-4 
    

    The difference with uint.MaxValue is:

    (2^32)-1 - ((2^32)-4) = 3
    

    To reach uint.MaxValue, another value, rand.Next(4) has to be added, thus we get:

    rand.Next() + rand.Next() + rand.Next(4)

    What's the chance to generate zero?

    Aproximately: 1/231 * 1/231 * 1/4 = 1/264, it should be 1/232

    Wait a second, what about:

    2 * rand.Next() + rand.Next(4)
    

    Again, what's the chance to generate zero?

    Aproximately: 1/231 * 1/4 = 1/233, too small to be truly random.

    Another easy example:

    rand.Next(2) + rand.Next(2), all possible results:

           0 + 0 = 0
           0 + 1 = 1
           1 + 0 = 1
           1 + 1 = 2
    

    Equal probabilities? No way José.

    Conclusion: The addition of true random numbers gives a random number, but not a true random number. Throw two fair dice ...

    0 讨论(0)
  • 2021-02-18 14:56

    Set the Range, " uint u0 <= returned value <= uint u1 ", using System.Random

    It is easier to start with a range from "zero" (inclusive) to "u" (inclusive).
    You might take a look at my other answer. If you are interested in a faster/more efficient way:
    Uniform pseudo random numbers in a range. (It is quite a lot of code/text).

    Below "rnd32(uint u)" returns: 0 <= value <= u .
    The most difficult case is: "u = int.MaxValue". Then the chance that the first iteration of the "do-loops"
    (a single iteration of both the outer and the inner "do-loop"), returns a valid value is 50%.
    After two iterations, the chance is 75%, etc.

    The chance is small that the outer "do-loop" iterates more than one time.
    In the case of "u = int.MaxValue": 0%.

    It is obvious that: "rnd32(uint u0, uint u1)" returns a value between u0 (incl) and u1 (incl).

    private static Random rand = new Random();
    
    private static uint rnd32(uint u)                                 //  0 <= x <= u
    {
        uint x;
        if (u < int.MaxValue) return (uint)rand.Next((int)u + 1);
        do                                         
        {
            do x = (uint)rand.Next(1 << 30) << 2;
            while (x > u);
            x |= (uint)rand.Next(1 << 2);
        }
        while (x > u);
        return x;
    }
    
    private static uint rnd32(uint u0, uint u1)                      // set the range
    {
        return u0 < u1 ? u0 + rnd32(u1 - u0) : u1 + rnd32(u0 - u1);
    }
    
    0 讨论(0)
  • 2021-02-18 15:12

    The simplest approach would probably be to use two calls: one for 30 bits and one for the final two. An earlier version of this answer assumed that Random.Next() had an inclusive upper bound of int.MaxValue, but it turns out it's exclusive - so we can only get 30 uniform bits.

    uint thirtyBits = (uint) random.Next(1 << 30);
    uint twoBits = (uint) random.Next(1 << 2);
    uint fullRange = (thirtyBits << 2) | twoBits;
    

    (You could take it in two 16-bit values of course, as an alternative... or various options in-between.)

    Alternatively, you could use NextBytes to fill a 4-byte array, then use BitConverter.ToUInt32.

    0 讨论(0)
提交回复
热议问题