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 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 .
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With