Reputation: 21
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
}
}
As a result of code above, sum is coming around 50 as expected
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
}
}
In that case sum should not be around 50. According to my calculation it should be 10 but it is also around 50. Can somebody explain why it happens like that ?
Upvotes: 2
Views: 92
Reputation: 7872
Welcome to StackOverflow.
I believe that your calculation are wrong.
In the second example you are asking the following question:
How much chances are they that
y
has been generated equal tox
.
But having X being being a static value or being generated randomly does not adds anything to the equation. You are just testing a random generation against a number. Due to the random nature of the process, the second example is prone to produce a output that might vary a bit more than the first example on small iterations, but with 250 iteration the randomness is more or less smoothed.
You have one chances out of five to have the same digits.
1/5 * 250 = 50
This is working as intended. You might have been thinking 1/5/5 * 250 ? which would have been with three random digits, aren't you?
Upvotes: 1