为什么“new Random().Next()"不返回像“random.Next()"这样的随机数? [英] Why does "new Random().Next()" not return random numbers like "random.Next()"?

查看:59
本文介绍了为什么“new Random().Next()"不返回像“random.Next()"这样的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了两种不同的方法来获取随机数序列:

I have tried two different ways to get a sequence of random numbers:

// (a) works
Random random = new Random();
return Enumerable.Range(0, 20).OrderBy(n => random.Next());

// (b) does not work
return Enumerable.Range(0, 20).OrderBy(n => new Random().Next());

我使用 random.Next() 的第一个变体工作正常.

The first variant, where I am using random.Next(), is working fine.

但是我调用 new Random().Next() 的变体不返回随机数;相反,它返回一个从 0 到 20 的数字序列.

But the variant, where I have call new Random().Next(), does NOT return random numbers; instead it returns a sequence of numbers from 0 to 20.

现在我的问题是:

  • 在 C# 中表示对象 new Random().Next() 的第二种初始化的术语是什么?
  • 它与第一个有什么不同,以至于我没有得到欲望输出?
  • What is term to denote the second type of initialization of object new Random().Next() in C#?
  • And how it is different from the first one so that I am not getting the desire output?

推荐答案

Random 类在构造时使用种子初始化 - 该种子将用于生成唯一的数字序列.如果未指定种子 - Environment.TickCount 用作种子.在您的情况下,序列构造得如此之快,以至于 Random 类在每个构造的实例中都获得相同的种子.所以所有项目都返回相同的值,而不是随机排序.

Random class initializes with seed on construction - this seed will be used to produce unique sequence of numbers. In case if seed is not specified - Environment.TickCount is used as seed. In your case, sequence is constructed so fast, that Random class gets same seed in every constructed instance. So all items return same value, and not randomly sorted.

另一方面,第一个工作行为每个可枚举项都有一个 Random 类实例.所以调用 .Next() 会产生下一个随机数,虽然种子是一样的,序列会随机排序.

First working line, on the other hand, have single Random class instance for every enumerable item. So calling .Next() produces next random number, although seed is the same, and sequence gets randomly sorted.

说到生成没有重复的随机序列 - 看看 Fisher-Yates 洗牌.您使用 Random() 的示例有副作用 - 执行每个循环迭代都会更改 Random() 类实例的内部状态,这可能导致不良行为 - 例如,如果排序算法依赖于每个序列项在排序期间返回相同数字的事实(.net 不是这种情况,但谁知道呢 - 内部实现可能会在未来发生变化).

Speaking of generating random sequences without duplicates - look at Fisher-Yates shuffle. Your example with Random() has side effects - executing every loop iteration changes internal state of Random() class instance, which can lead to undesired behavior - for example, if sorting algorithm relies on fact that each sequence item returns same number during sort (this is not the case with .net, but who knows - internal implementation may change in future).

这篇关于为什么“new Random().Next()"不返回像“random.Next()"这样的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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