Random Rolls of a Die
In the last webpage we surveyed how random numbers can be generated and
shifted to work for different ranges of equally likely values. Now
we need to determine how to simulate the rolling
of a single die using random numbers.
A single die, in theory, is supposed to equally likely turn up with either a 1, 2, 3, 4, 5 or 6. Notice how this is just somewhat different than what we did in the last webpage. Being more specific we need random numbers that have the following characteristics.
So it might not surprise you that we can pretty much make use of what we did in the last webpage but cast the results to an integer. But you also need to remember that when you cast double to integers it truncates them downward. So our function for for doing this will have to be the following.
|Everything is one higher than you'd expect from our
formula in the last webpage because we are casting them to integers as we
don't get zero on any rolls. The lowest value we can get is one.
Our first application that will generate and display 20 random rolls of a die and should be called RandomRolls,java.
public class RandomRolls
|When running this you should see something similar to the following output. Hopefully, the program uses a different seed number, such as the current time, to initialize the random( ) generated sequence of numbers so you should see somewhat different numbers.|
This program does the following
Frequency of Rolls. One of the ways that researchers try to validate the capability of an algorithm to generate the desired distribution of random numbers is to
In this vein we will generate 24,000 rolls of a die and count up how many times we get a 1, 2, 3, 4, 5 and/or 6. These results are done in the following application RollDieFrequency.java.
public class RollDieFrequency
|After running it you should see something like the following.|
|Notice how each value is relatively close to 4000, but
none of them is exact. How close should they be? That's a very
good question and outside the scope of this course.
The code can hopefully be better understood through the following outline.
face = 1 + (int)(Math.random( ) * 6)
This is all we will say on this topic.
In the next webpage we will develop some code to simulate playing the game of craps. You should make sure you know how to play the game before trying to understand the code. There is some discussion of the rules before we dig into the code in the next webpage.