How Java random generator works?

前端 未结 4 1166
天涯浪人
天涯浪人 2021-01-04 09:36

I wrote program that simulates dice roll

    Random r = new Random();
    int result = r.nextInt(6);
    System.out.println(result);

I want

4条回答
  •  悲哀的现实
    2021-01-04 10:30

    I want to know if there is a way to "predict" next generated number and how JVM determines what number to generate next?

    Absolutely. The Random class is implemented as a linear congruential number generator (LCNG). The general formula for a linear congruential generator is:

    new_state = (old_state * C1 + C2) modulo N
    

    The precise algorithm used by Random is specified in the javadocs. If you know the current state of the generator1, the next state is completely predictable.

    Will my code output numbers close to real random at any JVM and OS?

    If you use Random, then No. Not for any JVM on any OS.

    The sequence produced by an LCNG is definitely not random, and has statistical properties that are significantly different from a true random sequence. (The sequence will be strongly auto-correlated, and this will show up if you plot the results of successive calls to Random.nextInt().)

    Is this a problem? Well it depends on what your application needs. If you need "random" numbers that are hard to predict (e.g. for an algorithm that is security related), then clearly no. And if the numbers are going to be used for a Monte Carlo simulation, then the inate auto-correlation of a LCNG can distort the simulation. But if you are just building a solitaire card game ... it maybe doesn't matter.


    1 - To be clear, the state of a Random object consists of the values of its instance variables; see the source code. You can examine them using a debugger. At a pinch you could access them and even update them using Java reflection, but I would not advise doing that. The "previous" state is not recorded.

提交回复
热议问题