// random numbers // Originally by Raju Rohde from Spring 2000 // Spring 2001: cleaned up by DIS Spring 2001 // Fall 2001: added generalization, some other wording clarification public class random { public static void main(String[] args) { /**************************************************************** * Math.random() returns a random floating-point number between * * 0.0 (inclusive) and 1.0 (exclusive). * **************************************************************** * SYNTAX: double r = Math.random(); * * NOTATION: r is a value in [0,1) or 0<=r<1 * **************************************************************** * Need to SCALE and SHIFT into an appropriate range * * Need CASTing to produce Integer random numbers * * scaling: * * Math.random()*N; // [0.0,N) * * shifting: * * Math.random()+N; // [N,N+1) * * casting: * * (int) (Math.random()*N); // [0,N-1) * ****************************************************************/ /**************************************************************** * EXAMPLES: * ****************************************************************/ // Produce a double random number in the range [1.0,6.0): double rnd1 = Math.random()*5 + 1; // Produce an integer random number 0 or 1: int rnd2 = (int) (Math.random()*2); // Produce an integer random number 1, 2, 3, or 4: int rnd3 = (int) (Math.random()*4) + 1; /**************************************************************** * Generalization: * ****************************************************************/ // Produce a random interger between LOW and HIGH, inclusive: final int LOW = -3; final int HIGH = 2; int genRand = (int) (Math.random()*(HIGH-LOW+1)) + (int) LOW; System.out.println(genRand); } }