import java.security.SecureRandom;
public class Main {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
int sum = 0;
// generate random number 250 times
for(int i = 0; i < 250; i++) {
// generate random number between 1 and 5
int guess = 1 + secureRandom.nextInt(5);
// how many times occur number 3 between 1 and 5
if(guess == 3) {
sum++;
}
}
System.out.println(sum); // print sum
}
}
作为上述代码的结果,总和如预期的那样接近 50
import java.security.SecureRandom;
public class Test {
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
int sum = 0;
// generate random number 250 times
for(int i = 0; i < 250; i++) {
int guess1 = 1 + random.nextInt(5); // first random num
int guess2 = 1 + random.nextInt(5); // second random num
// if they are equal increase sum by one
if(guess1 == guess2) {
sum++;
}
}
System.out.println(sum); // print sum
}
}
在那种情况下,总和不应该在 50 左右。根据我的计算,它应该是 10,但它也在 50 左右。有人可以解释为什么会这样吗?
最佳答案
欢迎使用 StackOverflow。
我相信你的计算是错误的。
在第二个示例中,您要问以下问题:
How much chances are they that
y
has been generated equal tox
.
但是,让 X 成为静态值或随机生成并不会增加方程式的任何内容。您只是在针对一个数字测试随机生成。 由于过程的随机性,第二个示例在小迭代时产生的输出可能比第一个示例的变化稍大一些,但在 250 次迭代后,随机性或多或少被平滑了。
您有五分之一的机会拥有相同的数字。
1/5 * 250 = 50
这是按预期工作的。你可能一直在想 1/5/5 * 250 ?这应该是三个随机数字,不是吗?
关于Java随机数概率看起来不对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575708/