Generate random uint - c#

I need to generate random numbers with range for byte, ushort, sbyte, short, int, and uint. I am able to generate for all those types using the Random method in C# (e.g. values.Add((int)(random.Next(int.MinValue + 3, int.MaxValue - 2)));) except for uint since Random.Next accepts up to int values only.
Is there an easy way to generate random uint?

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.

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 ...

The easiest way to generate random uint:
uint ui = (uint) new Random().Next(-int.MaxValue, int.MaxValue);

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);
}

Shorely its as simple as this little example with min and max uint range?:
public static class Utility
{
public static uint RandomUInt(uint min, uint max, Random? rand = null)
{
if (min > max) (min, max) = (max, min);
int intMin = (int)(int.MinValue + min);
int intMax = (int)(int.MinValue + max);
int rInt = rand?.Next(intMin, intMax) ?? new Random().Next(intMin, intMax);
return (uint)(int.MaxValue + rInt + 1);
}
}
Utility.RandomUInt(3000000000, 3000000010);
Output:
| 3000000005
| 3000000001
| 3000000009

Related

C# - What's the fastest way to convert a number to the smallest BitArray

I would like to convert a number to a BitArray, with the resulting BitArray only being as big as it needs to be.
For instance:
BitArray tooBig = new BitArray(new int[] { 9 });
results in a BitArray with a length of 32 bit, however for the value 9 only 4 bits are required. How can I create BitArrays which are only as long as they need to be? So in this example, 4 bits. Or for the number 260 I expected the BitArray to be 9 bits long
You can figure out all the bits first and then create the array by checking if the least significant bit is 1 or 0 and then right shifting until the number is 0. Note this will not work for negative numbers where the 32nd bit would be 1 to indicate the sign.
public BitArray ToShortestBitArray(int x)
{
var bits = new List<bool>();
while(x > 0)
{
bits.Add((x & 1) == 1);
x >>= 1;
}
return new BitArray(bits.ToArray());
}
Assuming you are working with exclusively unsigned integers, the number of bits you need is equal to the base 2 logarithm of the (number+1), rounded up.
Counting the bits is probably the easiest solution.
In JavaScript for example...
// count bits needed to store a positive number
const bits = (x, b = 0) => x > 0 ? bits(x >> 1, b + 1) : b;

Minimum number of bits to represent number

What is the most efficient way to find out how many bits are needed to represent some random int number?
For example number 30,000 is represented binary with
111010100110000
So it needs 15 bits
You may try:
Math.Floor(Math.Log(30000, 2)) + 1
or
(int) Math.Log(30000, 2) + 1
int v = 30000; // 32-bit word to find the log base 2 of
int r = 0; // r will be lg(v)
while ( (v >>= 1) != 0) // unroll for more speed...
{
r++;
}
For more advanced methods, see here http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
Note that this computes the index of the leftmost set bit (14 for 30000). If you want the number of bits, just add 1.
Try log(number)/log(2). Then round it up to the next whole number.

Generate a Random Int32 for the full range of possible numbers

If I wanted to generate a random number for all possible numbers an Int32 could contain would the following code be a reasonable way of doing so? Is there any reason why it may not be a good idea? (ie. a uniform distribution at least as good as Random.Next() itself anyway)
public static int NextInt(Random Rnd) //-2,147,483,648 to 2,147,483,647
{
int AnInt;
AnInt = Rnd.Next(System.Int32.MinValue, System.Int32.MaxValue);
AnInt += Rnd.Next(2);
return AnInt;
}
You could use Random.NextBytes to obtain 4 bytes, then use BitConverter.ToInt32 to convert those to an int.
Something like:
byte[] buf = new byte[4];
Rnd.NextBytes(buf);
int i = BitConverter.ToInt32(buf,0);
Your proposed solution will slightly skew the distribution. The minValue and maxValue will occur less frequently than the interior values. As an example, assume that int has a MinValue of -2 and a MaxValue of 1. Here are the possible initial values, with each followed by the resulting values after the Random(2):
-2: -2 -1
-1: -1 0
0: 0 1
half of the negative -2 values will get modified up to -1, and only half of 0 will get modified up to 1. So the values -2 and 1 will occur less frequently than -1 and 0.
Damien's solution is good. Another choice would be:
if (Random(2) == 0) {
return Random(int.MinValue, 0);
} else {
return 1 + Random(-1, int.MaxValue);
}
another solution, similar to Damiens approach, and faster than the previous one would be
int i = r.Next(ushort.MinValue, ushort.MaxValue + 1) << 16;
i |= r.Next(ushort.MinValue, ushort.MaxValue + 1);
A uniform distribution does not mean you get each number exactly once. For that you need a permutation
Now, if you need a random permutation of all 4-billion numbers you're a bit stuck. .NET does not allow objects to be larger than 2GBs. You can work around that, but I assume that's not really what you need.
If you less numbers (say, 100, or 5 million, less than a few billions) without repetitions, you should do this:
Maintain a set of integers, starting empty. Choose a random number. If it's already in the set, choose another random number. If it's not in the set, add it and return it.
That way you guarantee each number will be returned only once.
I have a class where I get random bytes into a 8KB buffer and distribute numbers from by converting them from the random bytes. This gives you the full int distribution. The 8KB buffer is used to you do not need to call NextBytes for every new random byte[].
// Get 4 bytes from the random buffer and cast to int (all numbers equally this way
public int GetRandomInt()
{
CheckBuf(sizeof(int));
return BitConverter.ToInt32(_buf, _idx);
}
// Get bytes for your buffer. Both random class and cryptoAPI support this
protected override void GetNewBuf(byte[] buf)
{
_rnd.NextBytes(buf);
}
// cyrptoAPI does better random numbers but is slower
public StrongRandomNumberGenerator()
{
_rnd = new RNGCryptoServiceProvider();
}

Need a way to pick a common bit in two bitmasks at random

Imagine two bitmasks, I'll just use 8 bits for simplicity:
01101010
10111011
The 2nd, 4th, and 6th bits are both 1. I want to pick one of those common "on" bits at random. But I want to do this in O(1).
The only way I've found to do this so far is pick a random "on" bit in one, then check the other to see if it's also on, then repeat until I find a match. This is still O(n), and in my case the majority of the bits are off in both masks. I do of course & them together to initially check if there's any common bits at all.
Is there a way to do this? If so, I can increase the speed of my function by around 6%. I'm using C# if that matters. Thanks!
Mike
If you are willing to have an O(lg n) solution, at the cost of a possibly nonuniform probability, recursively half split, i.e. and with the top half of the bits set and the bottom half set. If both are nonzero then chose one randomly, else choose the nonzero one. Then half split what remains, etc. This will take 10 comparisons for a 32 bit number, maybe not as few as you would like, but better than 32.
You can save a few ands by choosing to and with the high half or low half at random, and if there are no hits taking the other half, and if there are hits taking the half tested.
The random number only needs to be generated once, as you are only using one bit at each test, just shift the used bit out when you are done with it.
If you have lots of bits, this will be more efficient. I do not see how you can get this down to O(1) though.
For example, if you have a 32 bit number first and the anded combination with either 0xffff0000 or 0x0000ffff if the result is nonzero (say you anded with 0xffff0000) conitinue on with 0xff000000 of 0x00ff0000, and so on till you get to one bit. This ends up being a lot of tedious code. 32 bits takes 5 layers of code.
Do you want a uniform random distribution? If so, I don't see any good way around counting the bits and then selecting one at random, or selecting random bits until you hit one that is set.
If you don't care about uniform, you can select a set bit out of a word randomly with:
unsigned int pick_random(unsigned int w, int size) {
int bitpos = rng() % size;
unsigned int mask = ~((1U << bitpos) - 1);
if (mask & w)
w &= mask;
return w - (w & (w-1));
}
where rng() is your random number generator, w is the word you want to pick from, and size is the relevant size of the word in bits (which may be the machine wordsize, or may be less as long as you don't set the upper bits of the word. Then, for your example, you use pick_random(0x6a & 0xbb, 8) or whatever values you like.
This function uniformly randomly selects one bit which is high in both masks. If there are
no possible bits to pick, zero is returned instead. The running time is O(n), where n is the number of high bits in the anded masks. So if you have a low number of high bits in your masks, this function could be faster even though the worst case is O(n) which happens when all the bits are high. The implementation in C is as follows:
unsigned int randomMasksBit(unsigned a, unsigned b){
unsigned int i = a & b; // Calculate the bits which are high in both masks.
unsigned int count = 0
unsigned int randomBit = 0;
while (i){ // Loop through all high bits.
count++;
// Randomly pick one bit from the bit stream uniformly, by selecting
// a random floating point number between 0 and 1 and checking if it
// is less then the probability needed for random selection.
if ((rand() / (double)RAND_MAX) < (1 / (double)count)) randomBit = i & -i;
i &= i - 1; // Move on to the next high bit.
}
return randomBit;
}
O(1) with uniform distribution (or as uniform as random generator offers) can be done, depending on whether you count certain mathematical operation as O(1). As a rule we would, though in the case of bit-tweaking one might make a case that they are not.
The trick is that while it's easy enough to get the lowest set bit and to get the highest set bit, in order to have uniform distribution we need to randomly pick a partitioning point, and then randomly pick whether we'll go for the highest bit below it or the lowest bit above (trying the other approach if that returns zero).
I've broken this down a bit more than might be usual to allow the steps to be more easily followed. The only question on constant timing I can see is whether Math.Pow and Math.Log should be considered O(1).
Hence:
public static uint FindRandomSharedBit(uint x, uint y)
{//and two nums together, to find shared bits.
return FindRandomBit(x & y);
}
public static uint FindRandomBit(uint val)
{//if there's none, we can escape out quickly.
if(val == 0)
return 0;
Random rnd = new Random();
//pick a partition point. Note that Random.Next(1, 32) is in range 1 to 31
int maskPoint = rnd.Next(1, 32);
//pick which to try first.
bool tryLowFirst = rnd.Next(0, 2) == 1;
// will turn off all bits above our partition point.
uint lowerMask = Convert.ToUInt32(Math.Pow(2, maskPoint) - 1);
//will turn off all bits below our partition point
uint higherMask = ~lowerMask;
if(tryLowFirst)
{
uint lowRes = FindLowestBit(val & higherMask);
return lowRes != 0 ? lowRes : FindHighestBit(val & lowerMask);
}
uint hiRes = FindHighestBit(val & lowerMask);
return hiRes != 0 ? hiRes : FindLowestBit(val & higherMask);
}
public static uint FindLowestBit(uint masked)
{ //e.g 00100100
uint minusOne = masked - 1; //e.g. 00100011
uint xord = masked ^ minusOne; //e.g. 00000111
uint plusOne = xord + 1; //e.g. 00001000
return plusOne >> 1; //e.g. 00000100
}
public static uint FindHighestBit(uint masked)
{
double db = masked;
return (uint)Math.Pow(2, Math.Floor(Math.Log(masked, 2)));
}
I believe that, if you want uniform, then the answer will have to be Theta(n) in terms of the number of bits, if it has to work for all possible combinations.
The following C++ snippet (stolen) should be able to check if any given num is a power of 2.
if (!var || (var & (var - 1))) {
printf("%u is not power of 2\n", var);
}
else {
printf("%u is power of 2\n", var);
}
If you have few enough bits to worry about, you can get O(1) using a lookup table:
var lookup8bits = new int[256][] = {
new [] {},
new [] {0},
new [] {1},
new [] {0, 1},
...
new [] {0, 1, 2, 3, 4, 5, 6, 7}
};
Failing that, you can find the least significant bit of a number x with (x & -x), assuming 2s complement. For example, if x = 46 = 101110b, then -x = 111...111010010b, hence x & -x = 10.
You can use this technique to enumerate the set bits of x in O(n) time, where n is the number of set bits in x.
Note that computing a pseudo random number is going to take you a lot longer than enumerating the set bits in x!
This can't be done in O(1), and any solution for a fixed number of N bits (unless it's totally really ridiculously stupid) will have a constant upper bound, for that N.

How to convert number to next higher multiple of five?

I am coding a program where a form opens for a certain period of time before closing. I am giving the users to specify the time in seconds. But i'd like this to be in mutliples of five. Or the number gets rounded off to the nearest multiple.
if they enter 1 - 4, then the value is automatically set to 5.
If they enter 6 - 10 then the value is automatically set to 10.
max value is 60, min is 0.
what i have, but i am not happy with this logic since it resets it to 10 seconds.
if (Convert.ToInt32(maskedTextBox1.Text) >= 60 || Convert.ToInt32(maskedTextBox1.Text) <= 0)
mySettings.ToastFormTimer = 10000;
else
mySettings.ToastFormTimer = Convert.ToInt32 (maskedTextBox1.Text) * 1000;
use the Modulus Operator
if(num % 5 == 0)
{
// the number is a multiple of 5.
}
what about this:
int x = int.Parse(maskedTextBox1.Text)/5;
int y = Math.Min(Math.Max(x,1),12)*5; // between [5,60]
// use y as the answer you need
5 * ((num - 1) / 5 + 1)
Should work if c# does integer division.
For the higher goal of rounding to the upper multiple of 5, you don't need to test whether a number is a multiple. Generally speaking, you can round-up or round-to-nearest by adding a constant, then rounding down. To round up, the constant is one less than n. Rounding an integer down to a multiple of n is simple: divide by n and multiply the result by n. Here's a case where rounding error works in your favor.
int ceil_n(int x, int n) {
return ((x+n-1) / n) * n;
}
In dynamic languages that cast the result of integer division to prevent rounding error (which doesn't include C#), you'd need to cast the quotient back to an integer.
Dividing by n can be viewed as a right-shift by 1 place in base n; similarly, multiplying by n is equivalent to a left-shift by 1. This is why the above approach works: it sets the least-significant digit of the number in base n to 0.
2410=445, 2510=505, 2610=515
((445+4 = 535) >>5 1) <<5 1 = 505 = 2510
((505+4 = 545) >>5 1) <<5 1 = 505 = 2510
((515+4 = 605) >>5 1) <<5 1 = 605 = 3010
Another way of zeroing the LSD is to subtract the remainder to set the least significant base n digit to 0, as Jeras does in his comment.
int ceil_n(int x, int n) {
x += n-1;
return x - x%n;
}

Categories

Resources