Can somebody verify this method. I need a long type number inside a range of two longs. I use the .NET Random.Next(min, max) function which return int's. Is my reasoning correct if I simply divide the long by 2, generate the random number and finally multiply it by 2 again? Or am I too enthusiastic... I understand that my random resolution will decrease but are there any other mistakes which will lead to no such a random number.
long min = st.MinimumTime.Ticks; //long is Signed 64-bit integer
long max = st.MaximumTime.Ticks;
int minInt = (int) (min / 2); //int is Signed 64-bit integer
int maxInt = (int) (max / 2); //int is Signed 64-bit integer
Random random = new Random();
int randomInt = random.Next(minInt, maxInt);
long randomLong = (randomInt * 2);
You can try
CryptoRandom
of the Inferno library:What's wrong with generating a
double
to be intended as a factor to be used to calculate the actuallong
value starting from the max value along
can be?!NextDouble
generates a random number between[0.0, 0.99999999999999978]
(msdn doc)You multiply this random number by your
maxLongValue
.You
Math.Round
that result so you can get the chance to getmaxLongValue
anyway (eg: simulate you got 1.0 from the NextDouble).long
.Start at the minimum, add a random percentage of the difference between the min and the max. Problem with this is that NextDouble returns a number x such that 0 <= x < 1, so there's a chance you'll never hit the max number.
Why don't you just generate two random
Int32
values and make oneInt64
out of them?Sorry, I forgot to add boundaries the first time. Added
min
andmax
params. You can test it like that:Values of
r
will lie in the desired range.EDIT: the implementation above is flawed. It's probably worth it to generate 4 16-bit integers rather than 2 32-bit ones to avoid signed-unsigned problems. But at this point the solution loses its elegancy, so I think it's best to stick with
Random.NextBytes
version:It looks pretty well in terms of value distribution (judging by very simple tests I ran).
This creates a random Int64 by using random bytes, avoiding modulo bias by retrying if the number is outside the safe range.
Some other answers here have two issues: having a modulo bias, and failing to correctly handle values of
max = long.MaxValue
. (Martin's answer has neither problem, but his code is unreasonably slow with large ranges.)The following code will fix all of those issues:
The following fully-documented class can be dropped into your codebase to implement the above solution easily and brain-free. Like all code on Stackoverflow, it's licensed under CC-attribution, so you can feel free to use to use it for basically whatever you want.
Usage: