Here's a bit of a puzzler: Random.Next()
has an overload that accepts a minimum value and a maximum value. This overload returns a number that is greater than or equal to the minimum value (inclusive) and less than the maximum value (exclusive).
I would like to include the entire range including the maximum value. In some cases, I could accomplish this by just adding one to the maximum value. But in this case, the maximum value can be int.MaxValue
, and adding one to this would not accomplish what I want.
So does anyone know a good trick to get a random number from int.MinValue
to int.MaxValue
, inclusively?
UPDATE:
Note that the lower range can be int.MinValue
but can also be something else. If I know it would always be int.MinValue
then the problem would be simpler.
It's actually interesting that this isn't the implementation for Random.Next(int, int), because you can derive the behavior of exclusive from the behavior of inclusive, but not the other way around.
Split the ranges in two, and compensate for the
MaxValue
:If we make the ranges of equal size, we can get the same result with different math. Here we rely on the fact that
int.MinValue = -1 - int.MaxValue
:Will this work for you?
The internal implementation of
Random.Next(int minValue, int maxValue)
generates two samples for large ranges, like the range betweenInt32.MinValue
andInt32.MaxValue
. For theNextInclusive
method I had to use another large rangeNext
, totaling four samples. So the performance should be comparable with the version that fills a buffer with 4 bytes (one sample per byte).Some results:
Update: My implementation has mediocre performance for the largest possible range (
Int32.MinValue
-Int32.MaxValue
), so I came up with a new one that is 4 times faster. It produces around 22,000,000 random numbers per second in my machine. I don't think that it can get any faster than that.Some results:
I'd suggest using
System.Numerics.BigInteger
like this:I tested it with
sbyte
.Distribution is OK.
You can try this. A bit hacky but can get you both min and max inclusive.