[java] Java random numbers using a seed

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?

This question is related to java random seed

The answer is


If you'd want to generate multiple numbers using one seed you can do something like this:

public double[] GenerateNumbers(long seed, int amount) {
    double[] randomList = new double[amount];
    for (int i=0;i<amount;i++) {
        Random generator = new Random(seed);
        randomList[i] = Math.abs((double) (generator.nextLong() % 0.001) * 10000);
        seed--;
    }
    return randomList;
}

It will display the same list if you use the same seed.


Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:

double randomGenerator() {
    return ThreadLocalRandom.current().nextDouble(0.5);
}

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.


Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state


The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.


You shouldn't be creating a new Random in method scope. Make it a class member:

public class Foo {
   private Random random 

   public Foo() {
       this(System.currentTimeMillis());
   }

   public Foo(long seed) {
       this.random = new Random(seed);
   }

   public synchronized double getNext() {
        return generator.nextDouble();
   }
}

This is only an example. I don't think wrapping Random this way adds any value. Put it in a class of yours that is using it.