我如何播种一个随机类以避免获得重复的随机值 [英] How do I seed a random class to avoid getting duplicate random values

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

问题描述

我在静态类的静态方法中有以下代码:

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

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

我把它放在一个循环中,而且我一直得到相同的 randomNumber

I have this inside a loop and I keep getting the same randomNumber!

这里有什么建议吗?

推荐答案

您不应在循环中创建新的 Random 实例.尝试类似:

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

由单个 Random 实例生成的随机数序列应该是均匀分布的.通过快速连续地为每个随机数创建一个新的 Random 实例,您可能会为它们设置相同的值并让它们生成相同的随机数.当然,在这种情况下,生成的序列将远非均匀分布.

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.

为了完整起见,如果您确实需要重新播种 Random,您将使用新种子创建 Random 的新实例:

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天全站免登陆