Random(long)构造函数有什么用? [英] What is the use of the Random(long) constructor?
问题描述
有2个随机
类的构造函数
-
public Random()
-
public Random(long seed)
public Random()
public Random(long seed)
第二个构造函数的描述符合 oracle 表示为
The description for the second constructor as per oracle states as
使用单个长种子创建新的随机数生成器。种子是伪随机数生成器的内部状态的初始值,它由方法next(int)维护。
Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).
我完全不理解它。我没有找到任何明确解释为什么, 以及 的文章/书籍。
I did not understand it completely. And I did not find any articles/book which clearly explains why,when and how it is used.
可以解释一下吗?
推荐答案
伪随机数生成器通过重复生成一个新的数字来工作在它之前生成的那个上。这意味着如果你总是拥有相同的第一个随机数字,并且你使用相同的伪随机数生成器来生成第二个,那么你将始终拥有相同的第二个 随机数字。
A pseudorandom number generator works by repeatedly generating a new number based on the one it has previously generated. That means that if you always have the same first "random" number, and you use the same pseudorandom number generator to generate the second, you'll always have the same second "random" number as well.
第一个随机
构造函数构造一个带有非确定种子的伪随机数生成器(第一个序列中的数字),所以你几乎总会得到一个不同的随机数字序列。第二个 Random
构造函数使用你想要的种子构造一个伪随机数生成器,所以如果你给它相同的种子,你总会得到相同的序列。
The first Random
constructor constructs a pseudorandom number generator with a nondeterminate seed (first number in the sequence), so you'll almost always end up with a different sequence of "random" numbers. The second Random
constructor constructs a pseudorandom number generator with whatever seed you want, so if you give it the same seed, you'll always get the same sequence.
这是一个例子。如果您创建 Random
,就像这样:
Here's an example. If you create a Random
like this:
Random yourRandom = new Random();
它将从一些种子开始。那种子可能是42,121,3810,无论如何。您永远无法确定何时创建它。它生成的所有随机数都是基于该种子的,所以因为它几乎总是使用不同的种子,所以你几乎总会得到不同的随机数字。
it will start off with some seed. That seed could be 42, 121, 3810, whatever. You can never be sure when you create it. All the random numbers it generates are based off of that seed, and so since it nearly always uses a different seed, you'll nearly always get different "random" numbers out of it.
另一方面,如果您改为创建一个 Random
:
On the other hand, if you create a Random
like this instead:
Random yourOtherRandom = new Random(36);
所有数字 yourOtherRandom
生成将被计算从36开始。因为第一个数字(36)是相同的,第二个数字是从第一个数字等计算的,所以 yourOtherRandom
生成的所有内容每次都是相同的你运行你的程序。
all the numbers yourOtherRandom
generates will be calculated starting from 36. Since the first number (36) is the same, and the second number is calculated from the first, etc., everything yourOtherRandom
generates will be the same every time you run your program.
这篇关于Random(long)构造函数有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!