Rahul Bhatia - 3 months ago 16

Java Question

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;

}

Everytime I give a seed and try to generate 100 numbers, they all are the same.

Please help.

Answer

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 : http://en.wikipedia.org/wiki/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 arg 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.

You code should probably be like this :

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