Java random numbers using a seed

Rahul Bhatia picture Rahul Bhatia · Sep 17, 2012 · Viewed 230.9k times · Source

This is my code to generate random numbers using a seed as an argument:

double randomGenerator(long seed) {
    Random generator = new Random(seed);
    double num = generator.nextDouble() * (0.5);

    return num;
}

Every time I give a seed and try to generate 100 numbers, they all are the same.
How can I fix this?

Answer

Denys Séguret picture Denys Séguret · Sep 17, 2012

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;
}