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?
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
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
Randominstance should of course be kept outside of your method.Your code should probably be like this: