jeudi 7 juillet 2016

Distribution of Random Numbers

I have two options of code:

Option 1

int myFunc() {
  return new Random().nextInt();
}

Or:

Option 2

private static final Random random = new Random();

int myFunc() {
  return random.nextInt();
}

IIUC option 2 will be less efficient in multithreaded environments (because it needs to lock on its internal state) so I would prefer to use option 1.

My question is regarding the distribution of the output of option 1. In option 1 I will only ever use the first number generated by a given seed. In option 2 I choose a seed and generate n numbers using that seed. IIUC the guarantees on randomness are on this use case. There can not be guarantees on option 1 because if I call it twice at the exact same time it will necessarily return the exact same output.

My question is, therefore, in real word applications (i.e. not in the mathematical sense) if I call option 1 many times in close succession (but never at the exact same instance) are there any guarantees on the uniformity of the distribution of the output?




Aucun commentaire:

Enregistrer un commentaire