长距离的随机数,是这种方式吗? [英] Random number in long range, is this the way?

查看:183
本文介绍了长距离的随机数,是这种方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以验证此方法。我需要一个长型的数字在两个长度的范围内。我使用.NET Random.Next(min,max)函数返回int。是我的推理正确,如果我简单除以长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 params。您可以像这样测试:

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.

EDIT:上述实现存在缺陷。它可能值得生成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);
}

在值分布方面看起来相当不错ran)。

It looks pretty well in terms of value distribution (judging by very simple tests I ran).

这篇关于长距离的随机数,是这种方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆