I need to generate random numbers with range for byte
, ushort
, sbyte
, short
, int
, and uint
. I am ab
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);
}