Playdowin - 2 months ago 11x

Java Question

I have encountered a problem considering the difference between the mathematical output and the one the program gives.

I want to count the probability of gaining the same number twice in 1/6 probability, which should be

`1 in 1/6 * 1/6 = 36`

`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);

}

Consider that I do this

`1000000`

`countGen`

Answer

Running the following code:

```
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));
```

Gives

27893 / 1000000

Or about 1 in 35.8512888538343

So, why do you get 1 in 42?

Consider, if you get 2 numbers the same, you increment `countReal`

. If you get 2 numbers the same a second time, you increment `countReal`

again (and then reset it to zero). If you get 2 numbers the same ** again**, you've already aborted counting your run. This

Shown another way:

```
int n = 1_000_000;
int count = 0;
Random rnd = new Random();
boolean matched_last_time = false;
for (int i = 0; i < n; i++) {
int a = rnd.nextInt(6);
int b = rnd.nextInt(6);
boolean match = a == b;
if (match && matched_last_time) {
count++;
// match = false; // Uncomment this line, & probability changes to 1 in 42
}
matched_last_time = match;
}
System.out.println(count + " / " + n);
System.out.println("Or about 1 in " + (n * 1.0 / count));
```

Source (Stackoverflow)

Comments