Random numbers
Navigate Language Fundamentals topic: ) |
To generate random numbers the Math.random()
method can be used, which returns a double
, greater than or equal to 0.0 and less than 1.0.
The following code returns a random integer between n and m (where n <= randomNumber < m):
Code section 3.30: A random integer.
int randomNumber = n + (int)(Math.random() * ( m - n ));
|
Alternatively, the java.util.Random
class provides methods for generating random boolean
s, byte
s, float
s, int
s, long
s and 'Gaussians' (double
s from a normal distribution with mean 0.0 and standard deviation 1.0). For example, the following code is equivalent to that above:
Code section 3.31: A random integer with Gaussian.
Random random = new Random();
int randomNumber = n + random.nextInt(m - n);
|
As an example using random numbers, we can make a program that uses a Random object to simulate flipping a coin 20 times:
|
|
Of course, if you run the program you will probably get different results.
Truly random numbers
[edit | edit source]Both Math.random()
and the Random
class produce pseudorandom numbers. This is good enough for a lot of applications, but remember that it is not truly random. If you want a more secure random number generator, Java provides the java.security.SecureRandom
package. What happens with Math.random()
and the Random
class is that a 'seed' is chosen from which the pseudorandom numbers are generated. SecureRandom
increases the security to ensure that the seed which is used by the pseudorandom number generator is non-deterministic — that is, you cannot simply put the machine in the same state to get the same set of results. Once you have created a SecureRandom
instance, you can use it in the same way as you can the Random
class.
If you want truly random numbers, you can get a hardware random number generator or use a randomness generation service.