Java Summary: Math.random() and java.util.Random

Math.random() method

A standard way to generate random numbers is to use the Math.random() method, which returens a double value in the range 0.0 up to, but not including 1.0. You can used multiplication to expand the range, addition to shift the range, and casting to convert it to an integer. The advantage of this method over the Random class (see below) is that there is no need to create an object. The disadvantage is that you often have to do more work to translate the return value into a range you want.

 double Math.random()

Returns a number x in the range, 0.0 <= x < 1.0.




java.util.Random Class
The java.util.Random class provides more flexible ways to generate uniformly distributed random numbers, providing easy generation of types other than double, as well as providing a Gaussian distribution.
Random Constructors
Random r =new Random(); Uses time in milliseconds as the seed.
Random r = new Random(long seed); Uses the provided seed for testing purposes.
Random Methods
All methods return a uniform distribution of values, except nextGaussian(). Assume r is a Random object..
int i = r.nextInt(int n) Returns random int >= 0 and < n.
int i = r.nextInt() Returns random int (full range).
long l = r.nextLong() Returns random long (full range).
float f = r.nextFloat() Returns random float >=0.0 and < 1.0.
double d = r.nextDouble() Returns random double >=0.0 and < 1.0.
boolean b = r.nextBoolean() Returns random boolean (true or false).
double d = r.nextGaussian() Returns random double with mean 0.0 and standard deviation 1.0.
Copyright 2005 Fred Swartz