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);
Is there anything wrong with using this simple approach?
d
How about generating bytes and converting to int64?
Sees to work for me (:
You're better off taking the difference between minimum and maximum (if it fits in an int), getting a random between 0 and that, and adding it to the minimum.
Your randomLong will always be even and you will have eliminated even more values because you are very far away from the maximum for
long
, The maximum for long is 2^32 * max for int. You should useRandom.NextBytes
.Here is a solution that leverages from the other answers using
Random.NextBytes
, but also pays careful attention to boundary cases. I've structured it as a set of extension methods. Also, I've accounted for modulo bias, by sampling another random number it falls out of range.One of my gripes (at least for the situation I was trying to use it) is that the maximum is usually exclusive so if you want to roll a die, you do something like
Random.Next(0,7)
. However, this means you can never get this overload to return the.MaxValue
for the datatype (int
,long
,ulong
, what-have-you). Therefore, I've added aninclusiveUpperBound
flag to toggle this behavior.