简体   繁体   中英

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:

  • 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?
  • once I process multiple objects and I take all first random numbers of all objects, will these will these form uniform random distribution (eg numbers 1, 6, 11, 16, 21) or this will be somehow broken?

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.

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.

•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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM