我想在java中生成随机数,我知道我应该使用像Math.random()这样的现有方法,但是,我的问题是:每次运行我的应用程序时,如何生成相同的数字序列?示例:生成的序列为:0.9,0.08,0.6所以我希望每次执行此方法时都会生成此序列.
Jon*_*eet 31
当然 - 只需创建一个Random而不是使用的实例Math.random(),并始终指定相同的种子:
Random random = new Random(10000); // Or whatever seed - maybe configurable
int diceRoll = random.nextInt(6) + 1; // etc
Run Code Online (Sandbox Code Playgroud)
请注意,如果您的应用程序涉及多个线程,则会变得更加困难,因为时间变得不那么可预测.
这利用Random了伪随机数生成器 - 换句话说,每当你要求它获得一个新结果时,它会操纵内部状态给你一个随机序列,但知道种子(或者实际上当前的内部状态) )它完全可以预测.
Pet*_*rey 26
重复使用相同种子的示例.
public static void main(String... args) throws IOException {
printDoublesForSeed(1);
printDoublesForSeed(128);
printDoublesForSeed(1);
printDoublesForSeed(128);
}
private static void printDoublesForSeed(long seed) {
double[] doubles = new double[10];
Random rand = new Random(seed);
for (int j = 0; j < doubles.length; j++) {
doubles[j] = (long) (rand.nextDouble() * 100) / 100.0;
}
System.out.println("doubles with seed " + seed + " " + Arrays.toString(doubles));
}
Run Code Online (Sandbox Code Playgroud)
版画
doubles with seed 1 [0.73, 0.41, 0.2, 0.33, 0.96, 0.0, 0.96, 0.93, 0.94, 0.93]
doubles with seed 128 [0.74, 0.53, 0.63, 0.41, 0.21, 0.2, 0.33, 0.74, 0.17, 0.47]
doubles with seed 1 [0.73, 0.41, 0.2, 0.33, 0.96, 0.0, 0.96, 0.93, 0.94, 0.93]
doubles with seed 128 [0.74, 0.53, 0.63, 0.41, 0.21, 0.2, 0.33, 0.74, 0.17, 0.47]
Run Code Online (Sandbox Code Playgroud)
编辑一个有趣的滥用随机种子.
public static void main(String ... args) {
System.out.println(randomString(-6225973)+' '+randomString(1598025));
}
public static String randomString(int seed) {
Random rand = new Random(seed);
StringBuilder sb = new StringBuilder();
for(int i=0;i<5;i++)
sb.append((char) ('a' + rand.nextInt(26)));
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
版画
hello world
Run Code Online (Sandbox Code Playgroud)
您需要为随机数生成器播种.
Random random = new Random(aFixedNumber);
random.nextInt(); // will always be the same
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7782 次 |
| 最近记录: |