我如何种子随机类,避免了重复的随机值 [英] How do I seed a random class to avoid getting duplicate random values

查看:181
本文介绍了我如何种子随机类,避免了重复的随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态方法里面以下code在静态类:

I have the following code inside a static method in a static class:

Random r = new Random();
int randomNumber = r.Next(1,100);

我有这样的一个循环中,我不断收到同样的 randomNumber

在这里有什么建议?

推荐答案

您不应该在一个循环中创建一个新的随机实例。尝试是这样的:

You should not create a new Random instance in a loop. Try something like:

var rnd = new Random();
for(int i = 0; i < 100; ++i) 
   Console.WriteLine(rnd.Next(1, 100));

由单个产生的随机数的序列的随机实例应该是均匀分布的。通过创建一个新的随机实例快速继承每一个随机数,你很可能具有相同值的种子他们,并让他们产生相同随机数。当然,在这种情况下,所生成的序列将远离均匀分布

The sequence of random numbers generated by a single Random instance is supposed to be uniformly distributed. By creating a new Random instance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.

有关完整起见,如果你真的需要补种一随机,您将创建随机的新实例与新种子:

For the sake of completeness, if you really need to reseed a Random, you'll create a new instance of Random with the new seed:

rnd = new Random(newSeed);

这篇关于我如何种子随机类,避免了重复的随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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