Fix my code to output like this. Count is how many rolls resulted in a sum of the X…
- User
Fix my code to output like this. Count is how many rolls resulted in a sum of the X amount Em Prob is the empirical probability from that simulation (count / numberRolled) P(X) is the theoretical probability:
2 Die Simulator
Theoretial Probability of rolling two die: X 2 3 4 5 6 7 8 9 10 11 12 P(X) 0.0278 0.0556 0.0833 0.1111 0.1389 0.1667 0.1389 0.1111 0.0833 0.0556 0.0278
Results Rolling 36 die: X 2 3 4 5 6 7 8 9 10 11 12 Count 1 2 3 7 2 7 7 3 3 1 0 Em Prob 0.0278 0.0556 0.0833 0.1944 0.0556 0.1944 0.1944 0.0833 0.0833 .0278 0
... countinue for 500 die and 10,000 die
import java.text.DecimalFormat; import java.util.Random; public class MyProgram { public static void main(String[] args) { int [] rollCounts = simulateDiceRolls(36); int [] rollCounts500 = simulateDiceRolls(500); int [] rollCounts10000 = simulateDiceRolls(10000); System.out.println("X\tCount\tEm Prob\tP(X)\t\tCount(500)\tEm Prob(500)\tCount(10000)\tEm Prob(10000)"); DecimalFormat df = new DecimalFormat("#.####"); for(int i = 2; i <=12; i++){ double theoreticalProbability = getTheoreticalProbability(i); System.out.printf("%d\t%d\t%s\t%s\t\t%d\t\t%s\t\t%d\t\t%s\n", i, rollCounts[i-2], df.format(rollCounts[i-2]/36.0), df.format(theoreticalProbability), rollCounts500[i-2], df.format(rollCounts500[i-2]/500.0), rollCounts10000[i-2], df.format(rollCounts10000[i-2]/10000.0)); }
code} public static int[] simulateDiceRolls(int numberOfRolls) { Random random = new Random(); int[] counts = new int[11]; for (int i = 0; i < numberOfRolls; i++) { int die1 = random.nextInt(6) + 1; int die2 = random.nextInt(6) + 1; int sum = die1 + die2; counts[sum - 2]++; } return counts; } public static double getTheoreticalProbability(int sum) { int[] occurrences = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; return occurrences[sum - 2] / 36.0; }}
- Assistant