Generate random numbers

Wednesday, 3 October 2012

There are two means of generating random (really pseudo-random) numbers :
the Random class generates random integers, doubles, longs and so on, in various ranges.
the static method Math.random generates doubles between 0 (inclusive) and 1 (exclusive). To generate random integers :
do not use Math.random (it produces doubles, not integers)
use the Random class to generate random integers between 0 and N.

To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number. See also the related Sun Tech Tip.

Another alternative is SecureRandom, a cryptographically strong subclass of Random. Example 1
 
import java.util.Random;

/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
  
  public static final void main(String... aArgs){
    log("Generating 10 random integers in range 0..99.");
    
    //note a single Random object is reused here
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      int randomInt = randomGenerator.nextInt(100);
      log("Generated : " + randomInt);
    }
    
    log("Done.");
  }
  
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 

Example 2 
This example generates random integers in a specific range.  
import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {
  
  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");
    
    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }
    
    log("Done.");
  }
  
  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }
  
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 
Share this article :

0 comments:

Speak up your mind

Tell us what you're thinking... !

Related Posts Plugin for WordPress, Blogger...
 
Support : Copyright © 2011. GL Entertaintment - All Rights Reserved
Proudly powered by Blogger