Tomas Greif
Tomas Greif

Reputation: 22661

Generate random numbers correctly

I would like to have 5 random numbers for every object I process. I process many objects (separately) and need to make sure that randomness is achieved across all numbers. If I process 5 objects, I will have 25 random numbers:

         RN1 RN2 RN3 RN4 RN5
Object 1   1   2   3   4   5
Object 2   6   7   8   9  10
Object 3  11  12  13  14  15
Object 4  16  17  18  19  20
Object 5  21  22  23  24  25

Questions are:

My view is that it would be best to create one random number generator only (shared by all objects) so that whenever new random number is required I can call nextDouble() and get next number in sequence of random numbers.

Upvotes: 2

Views: 198

Answers (3)

Roman
Roman

Reputation: 2365

The safest way is probably to preliminary generate the required number of random numbers, save it into an array, and establish the rules of access order. In such way you have full control over the process. There is also no "loss of randomness".

Otherwise, if you launch several generators at once, they most likely will be seeded with the same value (system time by default), and if you use single generator accessed simultaneously by different threads, you need to pass an object of Random class, which is may be good but also can lead to the loss of reproducibility (I'm not sure, if this is crucial in your case).

Upvotes: 1

jopasserat
jopasserat

Reputation: 5930

Have a look at the ThreadLocalRandom class from Java.

It provides uniform distribution and avoids bottleneck as each of your threads will have its own copy.

Regarding them having different sequences, it's all about changing their seed. One common practice in that case is to see the generator with the Thread/Task/Process's identifier.

Upvotes: 3

kutschkem
kutschkem

Reputation: 8163

•for single object, does it make a difference if I create random number generator for every single number using current time in milliseconds as seed or when I create one random number generator and get series of numbers using nextDouble in terms of randomness quality?

Don't use current time as seed for every number. The generation takes less time than the the resolution of current time in milliseconds.

Upvotes: 1

Related Questions