Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generation of the same sequence of random numbers

Tags:

java

I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers, each time I run my application? example: the generated sequence is: 0.9, 0.08,0.6 so I want that this sequence will be generated every time I execute this method..

like image 986
jojo Avatar asked Oct 26 '11 11:10

jojo


People also ask

What is a sequence of random numbers?

Random number generation is a process by which, often by means of a random number generator (RNG), a sequence of numbers or symbols that cannot be reasonably predicted better than by random chance is generated.

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function. Let's see how to set seed in Python pseudo-random number generator.

Why is rand generating the same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.


1 Answers

Sure - just create an instance of Random instead of using Math.random(), and always specify the same seed:

Random random = new Random(10000); // Or whatever seed - maybe configurable
int diceRoll = random.nextInt(6) + 1; // etc

Note that it becomes harder if your application has multiple threads involved, as the timing becomes less predictable.

This takes advantage of Random being a pseudo-random number generator - in other words, each time you ask it for a new result, it manipulates internal state to give you a random-looking sequence, but knowing the seed (or indeed the current internal state) it's entirely predictable.

like image 113
Jon Skeet Avatar answered Oct 05 '22 11:10

Jon Skeet