Case Study: Random-Number Generation

Case Study Random Number Generation

We now take a brief and, hopefully, entertaining diversion into a popular type of programming applicationsimulation and game playing. In this and the next section, we develop a nicely structured game-playing program with multiple methods. The program uses most of the control statements presented thus far in the book and introduces several new programming concepts.

There is something in the air of a casino that invigorates peoplefrom the high rollers at the plush mahogany-and-felt craps tables to the quarter poppers at the one-armed bandits. It is the element of chance, the possibility that luck will convert a pocketful of money into a mountain of wealth. The element of chance can be introduced in a program via an object of class Random (package java.util) or via the static method random of class Math. Objects of class Random can produce random boolean, byte, float, double, int, long and Gaussian values, whereas Math method random can produce only double values in the range 0.0 < x < 1.0, where x is the value returned by method random. In the next several examples, we use objects of class Random to produce random values.

A new random-number generator object can be created as follows:

 Random randomNumbers = new Random();

The random-number generator object can then be used to generate random boolean, byte, float, double, int, long and Gaussian valueswe discuss only random int values here. For more information on the Random class, see java.sun.com/j2se/5.0/docs/api/java/util/Random.html.

Consider the following statement:

 int randomValue = randomNumbers.nextInt();

Method nextInt of class Random generates a random int value in the range 2,147,483,648 to +2,147,483,647. If the nextInt method truly produces values at random, then every value in that range should have an equal chance (or probability) of being chosen each time method nextInt is called. The values returned by nextInt are actually pseudorandom numbersa sequence of values produced by a complex mathematical calculation. The calculation uses the current time of day (which, of course, changes constantly) to seed the random-number generator such that each execution of a program yields a different sequence of random values.

The range of values produced directly by method nextInt often differs from the range of values required in a particular Java application. For example, a program that simulates coin tossing might require only 0 for "heads" and 1 for "tails." A program that simulates the rolling of a six-sided die might require random integers in the range 16. A program that randomly predicts the next type of spaceship (out of four possibilities) that will fly across the horizon in a video game might require random integers in the range 14. For cases like these, class Random provides another version of method nextInt that receives an int argument and returns a value from 0 up to, but not including, the argument's value. For example, to simulate coin tossing, you might use the statement

 int randomValue = randomNumbers.nextInt( 2 );

which returns 0 or 1.

Rolling a Six-Sided Die

To demonstrate random numbers, let us develop a program that simulates 20 rolls of a six-sided die and displays the value of each roll. We begin by using nextInt to produce random values in the range 05, as follows:

 face = randomNumbers.nextInt( 6 );

The argument 6called the scaling factorrepresents the number of unique values that nextInt should produce (in this case six0, 1, 2, 3, 4 and 5). This manipulation is called scaling the range of values produced by Random method nextInt.

A six-sided die has the numbers 16 on its faces, not 05. So we shift the range of numbers produced by adding a shifting valuein this case 1to our previous result, as in

 face = 1 + randomNumbers.nextInt( 6 );

The shifting value (1) specifies the first value in the desired set of random integers. The preceding statement assigns face a random integer in the range 16.

Figure 6.7 shows two sample outputs which confirm that the results of the preceding calculation are integers in the range 16, and that each run of the program can produce a different sequence of random numbers. Line 3 imports class Random from the java.util package. Line 9 creates the Random object randomNumbers to produce random values. Line 16 executes 20 times in a loop to roll the die. The if statement (lines 2122) in the loop starts a new line of output after every five numbers, so the results can be presented on multiple lines.

Figure 6.7. Shifted and scaled random integers.

(This item is displayed on page 247 in the print version)

 1 // Fig. 6.7: RandomIntegers.java
 2 // Shifted and scaled random integers.
 3 import java.util.Random; // program uses class Random
 4
 5 public class RandomIntegers
 6 {
 7 public static void main( String args[] )
 8 {
 9 Random randomNumbers = new Random(); // random number generator
10 int face; // stores each random integer generated
11
12 // loop 20 times
13 for ( int counter = 1; counter <= 20; counter++ )
14 {
15 // pick random integer from 1 to 6 
16 face = 1 + randomNumbers.nextInt( 6 );
17
18 System.out.printf( "%d ", face ); // display generated value
19
20 // if counter is divisible by 5, start a new line of output
21 if ( counter % 5 == 0 )
22 System.out.println();
23 } // end for
24 } // end main
25 } // end class RandomIntegers
 
1 5 3 6 2
5 2 6 5 2
4 4 4 2 6
3 1 6 2 2
 
 
6 5 4 2 6
1 2 5 1 3
6 3 2 2 1
6 4 2 6 4
 

Rolling a Six-Sided Die 6000 Times

To show that the numbers produced by nextInt occur with approximately equal likelihood, let us simulate 6000 rolls of a die with the application in Fig. 6.8. Each integer from 1 to 6 should appear approximately 1000 times.

Figure 6.8. Rolling a six-sided die 6000 times.

(This item is displayed on pages 247 - 249 in the print version)

 1 // Fig. 6.8: RollDie.java
 2 // Roll a six-sided die 6000 times.
 3 import java.util.Random;
 4
 5 public class RollDie
 6 {
 7 public static void main( String args[] )
 8 {
 9 Random randomNumbers = new Random(); // random number generator
10
11 int frequency1 = 0; // maintains count of 1s rolled
12 int frequency2 = 0; // count of 2s rolled
13 int frequency3 = 0; // count of 3s rolled
14 int frequency4 = 0; // count of 4s rolled
15 int frequency5 = 0; // count of 5s rolled
16 int frequency6 = 0; // count of 6s rolled
17
18 int face; // stores most recently rolled value
19
20 // summarize results of 6000 rolls of a die
21 for ( int roll = 1; roll <= 6000; roll++ )
22 {
23 face = 1 + randomNumbers.nextInt( 6 ); // number from 1 to 6
24
25 // determine roll value 1-6 and increment appropriate counter
26 switch ( face )
27 {
28 case 1:
29 ++frequency1; // increment the 1s counter
30 break;
31 case 2:
32 ++frequency2; // increment the 2s counter
33 break;
34 case 3:
35 ++frequency3; // increment the 3s counter
36 break;
37 case 4:
38 ++frequency4; // increment the 4s counter
39 break;
40 case 5:
41 ++frequency5; // increment the 5s counter
42 break;
43 case 6:
44 ++frequency6; // increment the 6s counter
45 break; // optional at end of switch
46 } // end switch
47 } // end for
48
49 System.out.println( "Face	Frequency" ); // output headers
50 System.out.printf( "1	%d
2	%d
3	%d
4	%d
5	%d
6	%d
",
51 frequency1, frequency2, frequency3, frequency4,
52 frequency5, frequency6 );
53 } // end main
54 } // end class RollDie
 
Face Frequency
1 982
2 1001
3 1015
4 1005
5 1009
6 988
 
 
Face Frequency
1 1029
2 994
3 1017
4 1007
5 972
6 981
 

As the two sample outputs show, scaling and shifting the values produced by method nextInt enables the program to realistically simulate rolling a six-sided die. The application uses nested control statements (the switch is nested inside the for) to determine the number of times each side of the die occurred. The for statement (lines 2147) iterates 6000 times. During each iteration, line 23 produces a random value from 1 to 6. That value is then used as the controlling expression (line 26) of the switch statement (lines 2646). Based on the face value, the switch statement increments one of the six counter variables during each iteration of the loop. (When we study arrays in Chapter 7, we will show an elegant way to replace the entire switch statement in this program with a single statement!) Note that the switch statement has no default case because we have a case for every possible die value that the expression in line 23 could produce. Run the program several times, and observe the results. As you will see, every time you execute this program, it produces different results.

6.9.1. Generalized Scaling and Shifting of Random Numbers

Previously, we demonstrated the statement

 face = 1 + randomNumbers.nextInt( 6 );

which simulates the rolling of a six-sided die. This statement always assigns to variable face an integer in the range 1 < face < 6. The width of this range (i.e., the number of consecutive integers in the range) is 6, and the starting number in the range is 1. Referring to the preceding statement, we see that the width of the range is determined by the number 6 that is passed as an argument to Random method nextInt, and the starting number of the range is the number 1 that is added to randomNumberGenerator.nextInt( 6 ). We can generalize this result as


      number = shiftingValue + randomNumbers.nextInt( scalingFactor );

where shiftingValue specifies the first number in the desired range of consecutive integers and scalingFactor specifies how many numbers are in the range.

It is also possible to choose integers at random from sets of values other than ranges of consecutive integers. For example, to obtain a random value from the sequence 2, 5, 8, 11 and 14, you could use the statement

 number = 2 + 3 * randomNumbers.nextInt( 5 );

In this case, randomNumberGenerator.nextInt( 5 ) produces values in the range 04. Each value produced is multiplied by 3 to produce a number in the sequence 0, 3, 6, 9 and 12. We then add 2 to that value to shift the range of values and obtain a value from the sequence 2, 5, 8, 11 and 14. We can generalize this result as


      number = shiftingValue +
         differenceBetweenValues * randomNumbers.nextInt( scalingFactor );

where shiftingValue specifies the first number in the desired range of values, differenceBetweenValues represents the difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range.

6.9.2. Random-Number Repeatability for Testing and Debugging

As we mentioned earlier in Section 6.9, the methods of class Random actually generate pseudorandom numbers based on complex mathematical calculations. Repeatedly calling any of Random's methods produces a sequence of numbers that appears to be random. The calculation that produces the pseudorandom numbers uses the time of day as a seed value to change the sequence's starting point. Each new Random object seeds itself with a value based on the computer system's clock at the time the object is created, enabling each execution of a program to produce a different sequence of random numbers.

When debugging an application, it is sometimes useful to repeat the exact same sequence of pseudorandom numbers during each execution of the program. This repeatability enables you to prove that your application is working for a specific sequence of random numbers before you test the program with different sequences of random numbers. When repeatability is important, you can create a Random object as follows:

 Random randomNumbers = new Random( seedValue );

The seedValue argument (type long) seeds the random-number calculation. If the same seedValue is used every time, the Random object produces the same sequence of random numbers. You can set a Random object's seed at any time during program execution by calling the object's setSeed method, as in

 randomNumbers.setSeed( seedValue );

Error-Prevention Tip 6.2

While a program is under development, create the Random object with a specific seed value to produce a repeatable sequence of random numbers each time the program executes. If a logic error occurs, fix the error and test the program again with the same seed valuethis allows you to reconstruct the same sequence of random numbers that caused the error. Once the logic errors have been removed, create the Random object without using a seed value, causing the Random object to generate a new sequence of random numbers each time the program executes.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net