Generating Integer Random Numbers
There are many ways to generate random numbers with the base libraries found in the Java 2 SDK, Standard Edition. If you have not kept up to date with changes to the libraries, you might be using an inefficient mechanism or, possibly worse, getting Restributed. Here's a look at a good way to generate integer random number, and then a look at what's not so good about some.
The java.util.Random class has been available for generating random numbers since the initial release of the system libraries. Starting with the 1.2 release of the Java 2 SDK, Standard Edition, the Random class has a nextInt () method that accepts an integer Argument:
Public int nextint (INT N)
Given Some Value N, Nextint (n) Returns a value greater trun or equal to zero but less dam = = nextint (n) All you have to do is create a random Object First, THEN CALL NEXTINT (N) TO RETURN The Next Random Int Value. Here's a DemonStration. The Following Code Snippet Generates A Large Set of Random Numbers and Prints Out The average: INT count = 1000000; INT RANGE = INTEGER.MAX_VALUE / 3 * 2; Double Sum = 0; Random Rand = new random (); For (int i = 0; i Sum = rand.nextint (RANGE); } System.out.println (SUM / count); After Looping a Million Times, The Average Value Should Be Approximately At The Midpoint of The SELECTED RANGE. So Far, That Isn't Too Complicated, But What's Special About Using Nextint (N)? Why is using nextint (n) better Than (1) using the Older Nextint () Method, with no ing, the (2) USING MATH .abs () to get the absolute value, and then (3) using the mod (%) operator to get the value into the right range? The latter approach is demonstrated in the following code snippet. While there are a few extra operations in This approach, isn't it just as good as the first approach? sum = 0; For (int i = 0; i Sum = math.abs (rand.nextint ())% RANGE; } System.out.println (SUM / count); There Are Actually Three Problems with the latter approach. First, nextInt () is equally likely to return a value between Integer.MIN_VALUE and Integer.MAX_VALUE. If you take the absolute value of Integer.MIN_VALUE, the result is not a positive number. In fact, the result of Math.abs ( Integer.MIN_VALUE) is Integer.MIN_VALUE. So, on rare occasions, you'll get back a negative number. Given the rarity of the event, 1 out of 2 ^ 31 times, the likelihood of the event happening during testing, and being REPEATABLE, IS HIGHLY Unlikely. Second, when you mod (%) the results of nextInt (), you effectively reduce the randomness of the results. The low order bits of random numbers can repeat more regularly than the entire number. This is a known issue with pseudo-random number GENERATORS, AND SO IT's Another Reason Not to Use Mod (%). Finally, and possibly worst of all, the results are not evenly distributed. If you execute the loops in the two approaches, the first loop will produce results above 715 million, with a midpoint of the range at 715,827,882. That is within an acceptable tolerance for randomness. Surprisingly, the results of the second loop are consistently less than 600,000,000.How can the second loop be so far off base? Essentially, the problem is that the mapping is unfair. When you use the mod (%) operator, you are taking values that are too large and squeezing them into the low end. This favors the lesser values. Compare this to rolling a single die with three other friends. Because there are only four of you and six possible values, the mapping for the first Four Values IS Easy. Die Value 1 Is Mapped to Person 1, Value 2 To Person 2, And So on. Now What about the larues, 5 and 6? if you take the same approach as the mod (%) Operator, you Map The Large Values in Such A Way That ANY Time A 5 i S Rolled, Person 1 Wins, And Any Time A 6 IS ROLLED, PERSON 2 WINS. IS this fair? Well, That's what happens when you mod () The results of nextint (). Using the nextint (Range) Method Solves All Three of these problems. That Leaves The Random () Method of the Math Class As Another Possible Way To Generate Random Numbers. Using That Method Can't Be That Bad, Can IT? You Just Have To Multiply The Result by The Range: SUM = 0; For (int i = 0; i SUM = (int) (Math.random () * Range; } System.out.println (SUM / count); Well, Using this method (). You can't get a negative number back, you are not usning the mod (%) Operator so you don't run into the low- order byte range problem. and the range is uniform.What is the problem, though, is that Math.random () uses floating point arithmetic, and both versions of nextInt () work with only integer operations. Math.random () can be Up to four Times Slower Because of Its Use of floating point Operations. throw in the cast, and the Operation is Even Slower. Because It Avoids The Problems Inherent In Using The Other Approaches, Using The Nextint (Range) Method of Random IS A Better Way To Generate Integer Random Numbers. Here's a completion program you can use to test the different approaches discussed in this tip. Import java.util. *; Import java.text. *; Public class randomtest { Public static void main (string args []) { Numberformat nf = Numberformat.getInstance (); INT count = 1000000; INT RANGE = INTEGER.MAX_VALUE / 3 * 2; System.out.println ("Midpoint:" Nf.format (Range / 2)); Double Sum = 0; Random Rand = new random (); For (int i = 0; i Sum = rand.nextint (RANGE); } System.out.println ("Good:" Nf.format (sum / count); SUM = 0; For (int i = 0; i Sum = math.abs (rand.nextint ())% RANGE; } System.out.println ("BAD:" Nf.format (sum / count); SUM = 0; For (int i = 0; i SUM = (int) (Math.random () * Range; } System.out.println ("LONGER:" Nf.format (sum / count); } }