Random number in long range, is this the way?

2019-01-05 01:01发布

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

标签: c#-4.0 random
13条回答
贼婆χ
2楼-- · 2019-01-05 01:26

My worked solution. Tested for 1000+ times:

public static long RandomLong(long min, long max)
{
   return min + (long)RandomULong(0, (ulong)Math.Abs(max - min));
}
public static ulong RandomULong(ulong min, ulong max)
{
   var hight = Rand.Next((int)(min >> 32), (int)(max >> 32));
   var minLow = Math.Min((int)min, (int)max);
   var maxLow = Math.Max((int)min, (int)max);
   var low = (uint)Rand.Next(minLow, maxLow);
   ulong result = (ulong)hight;
   result <<= 32;
   result |= (ulong)low;
   return result;
}
查看更多
登录 后发表回答