Page 213 - Introduction to Programming with Java: A Problem Solving Approach
P. 213
int min = 1;
int max = 6;
5.8 Problem Solving with Random Numbers (Optional) 179 // fewest dots on one die
// most dots on one die
Then you shift and expand the basic random number, sort of like you did for the second type:
double r3 = min + (int) (Math.random() * (max - min + 1));
This time, you must remember that integer subtraction produces a distance that is one less than the number of integers in the range (6 minus 1 equals 5, not 6), so you have to add 1 to the difference like this (max - min + 1). The double returned by Math.random automatically promotes every- thing to double, so the shifted and expanded range is from 1.0 to 6.99999. The random selection gives equal weight to each of the six intervals above the integers of interest (1, 2, 3, 4, 5, and 6). The final (int) cast drops fractions.
4. For the fourth type (a discrete triangular distribution), at first you might think you could just use the third type with min = 2 and max = 12, but that would be wrong. It would generate just as many 2’s and 12’s as 7’s, but the chance of getting a 7 is actually six time higher than getting either a 2 or a 12! The most straightforward way to get the right answer is to call Math.random twice, and add the results:
int twoDice = r3 + r3;
5. The fifth type of distribution (a continuous exponential distribution) has been included because it’s used in models of many important real-world phenomena, like:
Inter-arrival time of automobiles at an isolated traffic light. Time between infrequent telephone calls.
Apago PDF Enhancer
Time between radioactive emissions from an unstable atom. Time to breakdown of a piece of machinery.
Time to failure of a semiconductor device.
To generate a random variable with a continuous exponential distribution, use a statement like this:
double r5 = -Math.log(1.0 - Math.random()) * averageTimeBetweenEvents;
The logarithm of zero is infinity, but that never occurs, because Math.random never generates a number ashighas1.0,so(1.0 - Math.random())isneveraslowaszero.
Using the Random class
Although it is possible to get any kind of distribution from Math.random, it’s not always
easy. For example, the algorithm you need to convert Math.random’s uniform distribu-
tion to a Gaussian (bell-curve) distribution is rather convoluted. So it would be nice to have
some pre-built methods that immediately generate random numbers from this and other
distributions. The Random class in the java.util package provides help. Here are API headings for some of the Random class methods:
public double nextDouble()
public int nextInt()
public int nextInt(int n)
public boolean nextBoolean()
public double nextGaussian()
Use the resource that fits best.