问题描述
有人可以验证这个方法吗?我需要在两个 long 范围内的 long 类型编号.我使用返回 int 的 .NET Random.Next(min, max) 函数.如果我简单地将 long 除以 2,生成随机数,最后再乘以 2,我的推理是否正确?还是我太热情了...我知道我的随机分辨率会降低,但是否还有其他错误会导致没有这样的随机数.
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);
推荐答案
为什么不直接生成两个随机的 Int32
值并从中生成一个 Int64
呢?
Why don't you just generate two random Int32
values and make one Int64
out of them?
long LongRandom(long min, long max, Random rand) {
long result = rand.Next((Int32)(min >> 32), (Int32)(max >> 32));
result = (result << 32);
result = result | (long)rand.Next((Int32)min, (Int32)max);
return result;
}
抱歉,我第一次忘记添加边界.添加了 min
和 max
参数.你可以这样测试:
Sorry, I forgot to add boundaries the first time. Added min
and max
params. You can test it like that:
long r = LongRandom(100000000000000000, 100000000000000050, new Random());
r
的值将在所需的范围内.
Values of r
will lie in the desired range.
上面的实现是有缺陷的.生成 4 个 16 位整数而不是 2 个 32 位整数以避免有符号无符号问题可能是值得的.但此时解决方案失去了优雅,所以我认为最好坚持使用 Random.NextBytes
版本:
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:
long LongRandom(long min, long max, Random rand) {
byte[] buf = new byte[8];
rand.NextBytes(buf);
long longRand = BitConverter.ToInt64(buf, 0);
return (Math.Abs(longRand % (max - min)) + min);
}
它在价值分布方面看起来相当不错(从我运行的非常简单的测试来看).
It looks pretty well in terms of value distribution (judging by very simple tests I ran).
这篇关于长范围内的随机数,是这样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!