Java Reference
In-Depth Information
Chapter 6
Random Numbers, Games,
and Simulation
In this chapter, we will explain the following:
Random numbers
The difference between random and pseudorandom numbers
How to generate random numbers on a computer
How to write a program to play a guessing game
How to write a program to drill a user in arithmetic
How to write a program to play Nim
How to simulate the collection of bottle caps to spell a word
How to simulate queues in real-life situations
How to estimate numerical values using random numbers
6.1 Random Numbers
If you were to throw a six-sided die 100 times, each time writing down the number that shows, you would have written
down 100 random integers uniformly distributed in the range 1 to 6.
If you tossed a coin 144 times and, for each toss, wrote down 0 (for heads) or 1 (for tails), you would have written
144 random integers uniformly distributed in the range 0 to 1.
If you were standing on the roadside and, as vehicles passed, you noted the last two digits of the registration
number (for those vehicles that have at least two digits), you would have noted random integers uniformly distributed
in the range 0 to 99.
Spin a roulette wheel (with 36 numbers) 500 times. The 500 numbers that appear are random integers uniformly
distributed in the range 1 to 36.
The word random implies that any outcome is completely independent of any other outcome. For instance, if a
5 showed on one throw of the die, then this has no bearing on what would show on the next throw. Similarly, a 29 on
the roulette wheel has no effect whatsoever on what number comes up next.
The term uniformly distributed means that all values are equally likely to appear. In the case of the die, you have
the same chance of throwing a 1 or a 6 or any other number. And, in a large number of throws, each number will occur
with roughly the same frequency.
 
Search WWH ::




Custom Search