In: Computer Science
Write a java program that simulates thousands of games and then calculate the probabilities from the simulation results. Specifically in the game, throw two dice, the possible summations of the results are: 2, 3, ..., 12. You need to use arrays to count the occurrence and store the probabilities of all possible summations. Try to simulate rolling two dice 100, 1000, 10,0000 times, or more if needed. Choose one simulation number so that the probabilities you calculated is within 1% absolute error compared with the theoretical probability. For example, the theoretical probability for summation result 2 is approximately 2.78%, then your calculated probability based on simulations should be between 2.28% and 3.28%. The following is required:
• Use an array of ints of length 11 to keep count of the difference occurrences. When an int or double array is created, its values are initialized to 0 by default.
• In the simulation loop, throw the two dice, add the values, and then increase the corresponding array element by 1.
• Turn the occurrence counts into probabilities after the simulation loop is done.
import java.util.Random;
public class Simulation {
public static void main(String[] args){
// Number of times simulation is run.
int N = 10000000;
double freq[] = new double[11];
Random rand = new Random();
for(int i=0;i<N;i++){
// Get 2 random numbers in range[1,6].
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
// sum them and add 1 to corresponding index in freq array.
int sum = roll1 + roll2;
freq[sum - 2]++;
}
// Find probability for each sum.
for(int i=0;i<11;i++){
double probabilty = freq[i]/N;
System.out.printf("Probabilty of sum %d = %f\n", i+2, probabilty);
}
}
}
I have used N = 10^7, and have gotten accurate results.
The output-
Theoretical Probability -
As we can see, the probabilities calculated are very accurate and have error of less than 1 percent.
The code has been commented so you can understand the code better.
I would love to resolve any queries in the comments. Please consider dropping an upvote to help out a struggling college kid :)
Happy Coding !!