Saturday 18 August 2012

Generate A Random Number Within a Range in Java

Java provides two classes to generate random numbers: Random and SecureRandom. Random is faster than SecureRandom, but it uses a 48 bits seeds which is not enough for the long type. Moreover, it is not 'random enough' for cryptography. SecureRandom, is slower than Random, but can be used for cryptography.

The following code example shows how to generate a random number within a range for int, long, float and double (inclusive means the max value is included for int and long):
int min = 122;
int max = 134;

SecureRandom rnd = new SecureRandom();
int inclusive = max - min + 1;
int exclusive = max - min;

int rndIntIncl = rnd.nextInt(inclusive) + min;
int rndIntExcl = rnd.nextInt(exclusive) + min;

System.out.println("Integer (incl.): " + rndIntIncl);
System.out.println("Integer (excl.): " + rndIntExcl);

long rndLongIncl = ( Math.abs(rnd.nextLong()) % inclusive ) + min;
long rndLongExcl = ( Math.abs(rnd.nextLong()) % exclusive ) + min;
System.out.println("Long    (incl.): " + rndLongIncl);
System.out.println("Long    (excl.): " + rndLongExcl);

float rndFloat = ( rnd.nextFloat() * exclusive ) + min;
System.out.println("Float          : " + rndFloat);

double rndDouble = ( rnd.nextDouble() * exclusive ) + min;
System.out.println("Double         : " + rndDouble);
The above generates something similar to this:
Integer (incl.): 129
Integer (excl.): 130
Long    (incl.): 125
Long    (excl.): 127
Float          : 125.42884
Double         : 127.84922531497857

No comments:

Post a Comment