概率计数中的Java输出
考虑到数学输出和程序给出的结果之间的差异,我遇到了一个问题 我想以1/6的概率计算两次获得相同数字的概率,这应该是概率计数中的Java输出,java,probability,Java,Probability,考虑到数学输出和程序给出的结果之间的差异,我遇到了一个问题 我想以1/6的概率计算两次获得相同数字的概率,这应该是1/6*1/6=36。然而,我得到的答案是1/42-43。怎么了 int guess = (int) (Math.random() * 6); int real = (int) (Math.random() * 6); int countTot = 0; int countReal = 0; int countGen = 0; while (true) { if (coun
1/6*1/6=36
。然而,我得到的答案是1/42-43。怎么了
int guess = (int) (Math.random() * 6);
int real = (int) (Math.random() * 6);
int countTot = 0;
int countReal = 0;
int countGen = 0;
while (true) {
if (countReal == 2) {
countGen++;
countReal = 0;
if (countGen == 1000000) {
System.out.println("Probability: 1 in " + countTot/countGen);
System.exit(0);
}
}
if (guess == real) {
countReal++;
countTot++;
} else {
countReal = 0;
countTot++;
}
guess = (int) (Math.random() * 6);
real = (int) (Math.random() * 6);
}
假设我做了1000000次(
countGen
),并取结果的平均值。提前感谢。运行以下代码:
int n = 1_000_000;
int count = 0;
Random rnd = new Random();
for (int i = 0; i < n; i++) {
int a = rnd.nextInt(6);
int b = rnd.nextInt(6);
int c = rnd.nextInt(6);
int d = rnd.nextInt(6);
if (a == b && c == d) {
count++;
}
}
System.out.println(count + " / " + n);
System.out.println("Or about 1 in " + (n * 1.0 / count));
你算错了。您正在将抛出次数(countTot)与成功的双重比较次数进行比较。你应该得到它1/72。但你们并没有得到它,因为若第一对不匹配,若提前退出 下面的代码给出了正确的答案。这不是很好,我会重新命名大多数东西,但我想保持它尽可能类似于原来的
int guess = (int) (Math.random() * 6);
int real = (int) (Math.random() * 6);
int countTot = 0;
int countReal = 0;
int countGen = 0;
while (true) {
if (countReal == 2) {
countGen++;
countReal = 0;
if (countGen == 1000000) {
System.out.println("Probability: 1 in " + (countTot/2)/countGen);
System.exit(0);
}
}
if (guess == real) {
countReal++;
countTot++;
} else {
countTot++;
if ( countReal == 0 ) {
countTot++;
}
countReal = 0;
}
guess = (int) (Math.random() * 6);
real = (int) (Math.random() * 6);
}
在不允许重叠的情况下计算连续匹配对的数量。如果你得到一个由3个相等的随机数组成的序列,你应该数到2对,但你只能数到一对。不允许重叠意味着一对取决于它之前的内容。为了能够增加概率,你必须保证事件是独立的。而且这个算法也比OP的算法更清晰。谢谢你的帮助,我现在明白了!谢谢你的帮助,我现在明白了!
int guess = (int) (Math.random() * 6);
int real = (int) (Math.random() * 6);
int countTot = 0;
int countReal = 0;
int countGen = 0;
while (true) {
if (countReal == 2) {
countGen++;
countReal = 0;
if (countGen == 1000000) {
System.out.println("Probability: 1 in " + (countTot/2)/countGen);
System.exit(0);
}
}
if (guess == real) {
countReal++;
countTot++;
} else {
countTot++;
if ( countReal == 0 ) {
countTot++;
}
countReal = 0;
}
guess = (int) (Math.random() * 6);
real = (int) (Math.random() * 6);
}