HELP! Please!!!
When you are rolling a six-side dice that has numbers 1 through 6, the odds of you getting any particular number should be the same, in theory, that is 0.17, or 1/6. Let’s how good Math.random()is for simulating rolling a dice. Write a program to do the following:
a.
Generate N random numbers in between 1 and 6, inclusive. You can either ask for user input for N or hardcode a literal value.
b.
Calculate the probability of getting a 4 using the following formula:
probability = number of 4s / N
c.
Prints out the probability.
How to write this java program (dice, probability)?
This isn't the prettiest code, but it should help:
int target_number = 4;
int target_number_count = 0;
int trials = 1000;
for (int i = 0; i %26lt; trials; i++) {
int random = (int) (Math.random() * 6) + 1;
if (random == target_number) {
target_number_count++;
}
}
double expected_percentage = 1.0 / 6;
double actual_percentage = (float) target_number_count / trials;
System.out.println("I ran " + trials + " runs of Java's random number generator, looking for the number'" + target_number + "'");
System.out.println("I expected to see " + (trials / 6) + " instances of that number (" + expected_percentage + "%)");
System.out.println("I actually saw " + target_number_count + " instances of that number (" + actual_percentage + "%)");
flash cards
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment