Java offers ready-made Random
class for creating random numbers. An instance of the Random class can be used as follows:
import java.util.Random;
public class Raffle {
public static void main(String[] args) {
Random ladyLuck = new Random(); // create Random object ladyLuck
for (int i = 0; i < 10; i++) {
// Draw and print a random number
int randomNumber = ladyLuck.nextInt(10);
System.out.println(randomNumber);
}
}
}
nextInt
gives between 0 and n - 1.
We can use the nextInt
method to create diverse randomness. For example, we might need a program to give us a temperature between [-30,50]. We can do this by first creating random a number between 0 and 80 and then subtracting 30 from it.
random.nextGaussian()
returns a normally distributed number (normally distributed numbers can be used to for example model the heights and weights of people.
Random numbers used by computer programs are typically pseudorandom. They seem like random numbers, but in reality they follow some algorithmically created series of numbers. Most of the time pseudorandom is good enough. On the other hand if random numbers are used for scientific calculations, using a weak pseudorandom number generator can lead to questionable results.
All randomness in computer programs is not pseudorandom. Programs aiming for stronger randomness use, among other things, real life random phenomena to generate random numbers. For example space radiation or lava lamps are thought to be random phenomena.