Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java random numbers using a seed

Tags:

java

random

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?

like image 279
Rahul Bhatia Avatar asked Sep 17 '12 11:09

Rahul Bhatia


People also ask

How does Java random work with seed?

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random .

How do you generate a random number from a seed?

You can mimic randomness by specifying a set of rules. For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let's take the starting number 77: Add 900 + 77 = 977.

How do you use random seed?

Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.

What is seed number in Java?

A seed is a number or a vector assigned to a pseudo-random generator to produce the required sequence of random values. If we pass the same seed, it will generate the same sequence. We usually assign the seed as system time. This way, it will produce a different sequence every time.


1 Answers

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; } 
like image 186
Denys Séguret Avatar answered Oct 02 '22 16:10

Denys Séguret