运行 不同时随机输出不同
Different random output when run differently
我正在尝试解决一个问题:-
一个点位于初始位置 X。它可以向左或向右移动。如果它以相同的概率向左或向右移动 10 次,它到达初始位置 X 的概率是多少?
我使用了以下 java 程序:-
import java.util.Random;
public class ProbMain {
int left;
int right;
int error;
double middle;
public ProbMain() {
left = right = error = 0;
middle = 0.0;
}
void pushLeft() {
++left;
}
void pushRight() {
++right;
}
void push() {
int whichWay;
Random rand = new Random();
whichWay = rand.nextInt(2);
if (whichWay == 0)
pushLeft();
else if (whichWay == 1)
pushRight();
else
++error;
}
public static void main(String[] args) {
ProbMain obj = new ProbMain();
for (int b = 0; b < 10000; b++) {
for (int a = 0; a < 10000; a++) {
for (int i = 0; i < 10; i++)
obj.push();
if (obj.left == obj.right)
++obj.middle;
obj.left = obj.right = 0;
}
}
System.out.println("Error: " + obj.error);
System.out.println("Probability of middle: " + obj.middle / (10000*10000));
}
}
奇怪的是,当我在 Eclipse 上 运行 时,我得到的结果约为 0.05,但是当我从命令行 运行 时,我得到的结果约为 0.24。为什么这样?哪一个是正确的?
每次要检索随机数(在 push()
方法中)时,您都在创建一个新的 Random
对象 - 这会导致非常差的熵,并在程序运行时产生奇怪的结果运行 具有不同的时间 - 由于附加的调试器,通常 运行来自 eclipse 的 ning 会慢得多,当 RNG 使用时间值作为种子初始化时,这将产生更好的随机结果。
您应该将您的程序更改为仅使用一个 Random
实例,例如通过声明一个新的 Random
成员变量并在 ProbMain
构造函数中将其初始化一次。
我正在尝试解决一个问题:- 一个点位于初始位置 X。它可以向左或向右移动。如果它以相同的概率向左或向右移动 10 次,它到达初始位置 X 的概率是多少? 我使用了以下 java 程序:-
import java.util.Random;
public class ProbMain {
int left;
int right;
int error;
double middle;
public ProbMain() {
left = right = error = 0;
middle = 0.0;
}
void pushLeft() {
++left;
}
void pushRight() {
++right;
}
void push() {
int whichWay;
Random rand = new Random();
whichWay = rand.nextInt(2);
if (whichWay == 0)
pushLeft();
else if (whichWay == 1)
pushRight();
else
++error;
}
public static void main(String[] args) {
ProbMain obj = new ProbMain();
for (int b = 0; b < 10000; b++) {
for (int a = 0; a < 10000; a++) {
for (int i = 0; i < 10; i++)
obj.push();
if (obj.left == obj.right)
++obj.middle;
obj.left = obj.right = 0;
}
}
System.out.println("Error: " + obj.error);
System.out.println("Probability of middle: " + obj.middle / (10000*10000));
}
}
奇怪的是,当我在 Eclipse 上 运行 时,我得到的结果约为 0.05,但是当我从命令行 运行 时,我得到的结果约为 0.24。为什么这样?哪一个是正确的?
每次要检索随机数(在 push()
方法中)时,您都在创建一个新的 Random
对象 - 这会导致非常差的熵,并在程序运行时产生奇怪的结果运行 具有不同的时间 - 由于附加的调试器,通常 运行来自 eclipse 的 ning 会慢得多,当 RNG 使用时间值作为种子初始化时,这将产生更好的随机结果。
您应该将您的程序更改为仅使用一个 Random
实例,例如通过声明一个新的 Random
成员变量并在 ProbMain
构造函数中将其初始化一次。