播种在C#的伪随机数发生器 [英] Seeding a pseudo-random number generator in C#

查看:110
本文介绍了播种在C#的伪随机数发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为C#的的实例种子随机类,我看大多数人使用当前时间的计数器蜱这一点。但是,这是一个64位的值和种子必须是32位的值。现在,我认为的GetHashCode()方法,它返回一个 INT ,应该为它的对象提供一个合理的分配值并且这可以用于避免使用滴答计数的只有较低的32位。但是,我找不到有关的GetHashCode的的Int64 数据类型的任何东西()。

I need a seed for an instance of C#'s Random class, and I read that most people use the current time's ticks counter for this. But that is a 64-bit value and the seed needs to be a 32-bit value. Now I thought that the GetHashCode() method, which returns an int, should provide a reasonably distributed value for its object and this may be used to avoid using only the lower 32-bits of the tick count. However, I couldn't find anything about the GetHashCode() of the Int64 datatype.

所以,我知道它将没有多大关系,而将下面的工作一样好,我觉得(我不能尝试和错误随机性),或者它的工作原理与使用(INT)DateTime.Now .Ticks 作为种子?或者,也许它甚至还可以更糟? 。谁可以阐明这光

So, I know that it will not matter much, but will the following work as good as I think (I can't trial-and-error randomness), or maybe it works the same as using (int)DateTime.Now.Ticks as the seed? Or maybe it even works worse? Who can shed some light on this.

int seed = unchecked(DateTime.Now.Ticks.GetHashCode());
Random r = new Random(seed);



编辑:为什么我需要一个种子,不只是让随机()构造函数做的工作?我需要发送种子到使用相同的随机序列相同的种子其他客户端。

Why I need a seed and don't just let the Random() constructor do the work? I need to send the seed to other clients which use the same seed for the same random sequence.

推荐答案

新的随机()已经使用了当前的时间。它等同于新的随机(Environment.TickCount)

new Random() already uses the current time. It is equivalent to new Random(Environment.TickCount).

但是,这是一个实现细节,可能会改变.NET的未来版本

But this is an implementation detail and might change in future versions of .net

我推荐使用新的随机(),只有当你想要得到的伪随机值的可重复序列提供固定的种子。

I'd recommend using new Random() and only provide a fixed seed if you want to get a reproducible sequence of pseudo random values.

既然你需要一个已知的种子只需要使用 Environment.TickCount 就像MS一样。然后将其传输到其他程序的实例作为种子。

Since you need a known seed just use Environment.TickCount just like MS does. And then transmit it to the other program instances as seed.

如果你在很短的创建随机的多个实例间隔(可以是16毫秒),他们可以接种到相同的值,并因此产生相同的伪随机序列。但是,这是最有可能不是一个问题在这里。这种常见的错误是由更新当前时间窗( DateTime.Now / .UtcNow )和计时单位计数(由于 Environment.TickCount )只每隔几毫秒。确切的时间间隔取决于Windows版本和以什么其他程序正在运行。典型的间隔,他们不改变是16毫秒或1毫秒。

If you create multiple instances of Random in a short interval (could be 16ms) they can be seeded to the same value, and thus create the same pseudo-random sequence. But that's most likely not a problem here. This common pitfall is caused by windows updating the current time(DateTime.Now/.UtcNow) and the TickCount(Environment.TickCount) only every few milliseconds. The exact interval depends on the version of windows and on what other programs are running. Typical intervals where they don't change are 16ms or 1ms.

这篇关于播种在C#的伪随机数发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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