I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers,
Math.random
is just a wrapper of the class java.util.Random
. The first time you call Math.random
an instance of the class java.util.Random
is created.
Now, most API's don't expose any true random number generators, because they cannot be implemented in software. Instead, they use pseudo-random number generators, which generate a sequence of random-looking numbers using a bunch of formulas. This is what java.util.Random
does. However, every pseudo-random number generator needs to be seeded first. If you have two pseudo-random number generators which use the same algorithm and use the same seed, they will produce the same output.
By default, java.util.Random
uses the milliseconds since January 1, 1970 as the seed. Therefore, everytime you start your program, it will produce different numbers (unless you manage it to start java up in under 1 millisecond). So, the solution to your problem is to create your own java.util.Random
instance and seed it by yourself:
import java.util.Random;
class ... {
Random randomNumberGenerator = new Random(199711);
public void ...()
{
int randomInt = randomNumberGenerator.nextInt();
double randomDouble = randomNumberGenerator.nextDouble();
}
}
The randomNumberGenerator
will always spit out the same sequence of numbers, as long as you don't change the seed(the 199711
).