我在脑海中有一个大问题:
I have a big question in my mind:
我可以使用种子数生成随机数:
I can use a seed number to generate random numbers:
Random rand = new Random(34666666);但是我无法理解的是种子的作用.例如
But the thing that I cannot understand is the role of that seed. For example what is the difference of
该代码包含以下内容:
Random rand = new Random();推荐答案
当您提供特定的,硬编码的种子时,请提供给one-arg Random构造函数,每次运行程序时,将生成的随机数始终相同.当您需要可预测的随机数源时就需要这样做.
When you supply a specific, hard-coded seed, to the one-arg Random constructor, the random numbers that will be generated will always be the same, every time you run the program. That is needed when you need a predictable source of random numbers.
但是,当您不提供种子时,请 Random构造函数将根据System.nanoTime为您选择一个种子.每次运行程序时,随机数都会不同,因为种子每次都会不同.
However, when you don't supply a seed, then the Random constructor will choose a seed for you, based on System.nanoTime. The random numbers will be different every time you run the program, because the seed will be different each time.
创建一个新的随机数生成器.该构造函数将随机数生成器的种子设置为一个很可能与该构造函数的任何其他调用不同的值.
Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.
这很重要,因为Java的随机数生成器是伪随机的.每个新的伪随机数都会影响用于生成下一个伪随机数的种子.
This is important because Java's random number generator is pseudo-random; each new pseudo-random number affects the seed that is used for the next pseudo-random number that gets generated.
更多推荐
种子在随机数生成中的作用
发布评论