生成相同的随机数序列

生成相同的随机数序列

本文介绍了生成相同的随机数序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在java中生成随机数,我知道我应该使用像Math.random()这样的现有方法,但是,我的问题是:每次运行我的应用程序时,如何生成相同的数字序列?
示例:生成的序列是:0.9,0.08,0.6
所以我希望每次执行此方法时都会生成此序列..

I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers, each time I run my application?example: the generated sequence is: 0.9, 0.08,0.6so I want that this sequence will be generated every time I execute this method..

推荐答案

当然 - 只需创建一个而不是使用 Math.random(),并始终指定相同的种子:

Sure - just create an instance of Random instead of using Math.random(), and always specify the same seed:

Random random = new Random(10000); // Or whatever seed - maybe configurable
int diceRoll = random.nextInt(6) + 1; // etc

请注意,如果您的应用程序涉及多个线程会变得更难,因为时间变得更少可预测。

Note that it becomes harder if your application has multiple threads involved, as the timing becomes less predictable.

这利用了 Random 作为 - 换句话说,每当你要求它获得一个新结果时,它会操纵内部状态给你一个随机序列,但知道种子(或确实是当前的内部状态)它完全可以预测。

This takes advantage of Random being a pseudo-random number generator - in other words, each time you ask it for a new result, it manipulates internal state to give you a random-looking sequence, but knowing the seed (or indeed the current internal state) it's entirely predictable.

这篇关于生成相同的随机数序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:28