Possible Duplicate:
True random generation in Java
Java random always returns the same number when I set the seed?
我在我的一个程序中运行这段代码。
public String[] gen_phase_zero() {
Random generator = new Random();
int r = generator.nextInt(2);
if (r == 1) {
String big = "A";
String small = "a";
return new String[] { big, small };
} else {
String big = "B";
String small = "b";
return new String[] { big, small };
}
}
如果我运行几次,我的输出就是这样的。
Aa 氨基酸 氨基酸 氨基酸 BB 氨基酸 氨基酸 氨基酸 BB
并不总是按这个顺序。但几乎从来没有接近 50/50
更新:
我不期望有五十五十,但似乎如果先选择“Aa”,那么接下来大约会再选择3次,但如果先选择Bb,那么接下来的3次就会被选择也是如此。
最佳答案
嗯,对我来说,这看起来还不错。让我们创建一个更具统计意义的测试:
import java.util.Random;
public class Test {
public static void main(String[] args) throws Exception {
Random rng = new Random();
int total = 0;
for (int i = 0; i < 1000000; i++) {
total += rng.nextInt(2);
}
System.out.println("Total: " + total);
}
}
5 次运行的示例输出:
Total: 501184
Total: 499740
Total: 500116
Total: 500374
Total: 500413
看起来对我来说并没有太大的偏见......
在循环内调用 new Random()
而不是只调用一次时,我也得到了相同的结果 - 尽管这样做不是一个好主意。
关于java - java中的随机生成方法看起来并不随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333779/