Java随机生成器如何工作? [英] How Java random generator works?

查看:98
本文介绍了Java随机生成器如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了模拟骰子滚动的程序

I wrote program that simulates dice roll

    Random r = new Random();
    int result = r.nextInt(6);
    System.out.println(result);

我想知道是否有办法预测下一个生成的数字以及JVM如何确定生成下一个数字?

I want to know if there is a way to "predict" next generated number and how JVM determines what number to generate next?

我的代码在任何JVM和操作系统上输出的数字是否接近真实随机?

Will my code output numbers close to real random at any JVM and OS?

推荐答案

它们是伪随机数,这意味着对于一般意图和目的,它们是随机的。然而,它们是确定性的,完全依赖于种子。以下代码将两次打印相同的10个数字。

They're pseudorandom numbers, meaning that for general intents and purposes, they're random enough. However they are deterministic and entirely dependent on the seed. The following code will print out the same 10 numbers twice.

Random rnd = new Random(1234);
for(int i = 0;i < 10; i++)
    System.out.println(rnd.nextInt(100));

rnd = new Random(1234);
for(int i = 0;i < 10; i++)
    System.out.println(rnd.nextInt(100));

如果您可以选择种子,您可以先预先计算数字,然后使用相同的方法重置发生器种子,你会提前知道出现了什么数字。

If you can choose the seed, you can precalculate the numbers first, then reset the generator with the same seed and you'll know in advance what numbers come out.

这篇关于Java随机生成器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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