Java Reference
In-Depth Information
Your turn: 4
Matches remaining: 9
I pick up 2
Matches remaining: 7
Your turn: 9
Cannot pick up more than 5
Your turn: 2
Matches remaining: 5
I pick up 4
Matches remaining: 1
I win!!
We note, in passing, that it would be useful to provide instructions for the game when it is run.
6.7 Nonuniform Distributions
So far, the random numbers we have generated have been uniformly distributed in a given range. For instance, when
we generated numbers from 10 to 99, each number in that range had the same chance of being generated. Similarly,
the call random(1, 6) will generate each of the numbers 1 to 6 with equal probability.
Now suppose we want the computer to “throw” a six-sided die. Since the computer can't physically throw the
die, it has to simulate the process of throwing. What is the purpose of throwing the die? It is simply to come up with a
random number from 1 to 6. As we have seen, the computer knows how to do this.
If the die is fair, then each of the faces has the same chance of showing. To simulate the throwing of such a die, all we
have to do is generate random numbers uniformly distributed in the range 1 to 6. We can do this with random(1, 6) .
Similarly, when we toss a fair coin, heads and tails both have the same chance of showing. To simulate the tossing
of such a coin on a computer, all we have to do is generate random numbers uniformly distributed in the range 1 to 2 .
We can let 1 represent heads and 2 represent tails.
In general, if all possible occurrences of an event (such as throwing a fair die) are equally likely, we can use
uniformly distributed random numbers to simulate the event. However, if all occurrences are not equally likely, how
can we simulate such an event?
To give an example, consider a biased coin, which comes up heads twice as often as tails. We say that the probability
of heads is 2/3 and the probability of tails is 1/3. To simulate such a coin, we generate random numbers uniformly
distributed in the range 1 to 3 . If 1 or 2 occurs, we say that heads was thrown; if 3 occurs, we say that tails was thrown.
Thus, to simulate an event that has a nonuniform distribution, we convert it to one in which we can use
uniformly distributed random numbers.
For another example, suppose that, for any day of a given month (June, say), we know the following, and only
these conditions are possible:
probability of sun = 4/9
probability of rain = 3/9
probability of overcast = 2/9
We can simulate the weather for June as follows:
for each day in June
r = random(1, 9)
if (r <= 4) "the day is sunny"
else if (r <= 7) "the day is rainy"
else "the day is overcast"
endfor
 
Search WWH ::




Custom Search