Random class acting odd?

后端 未结 6 742
粉色の甜心
粉色の甜心 2020-12-03 21:33

In this code:

Random random = new Random(441287210);
for(int i=0;i<10;i++)
    System.out.print(random.nextInt(10)+\" \");
}

The output

6条回答
  •  我在风中等你
    2020-12-03 22:11

    Random is a linear congruential generator; i.e. it is based on a formula of the form:

    N <- (N * C1 + C2) % M
    

    where C1, C2 and M are constants.

    One of the properties of this class of generator is that has high auto-correlation. Indeed, if you plot successive numbers you can see clear stripping patterns in the numbers.

    Your test program has effectively taken 10 successive numbers from the underlying generator, calculated their value modulo 10 ... and found that they are all the same. Effectively, the modulo 10 is "resonating" with the natural periodicity of the generator ... over a short period of time.

    This is one of the downsides of using a PRNG with high auto-correlation. In layman's terms ... it is "not very random" ... and you can get into trouble if you use it in a situation where randomness is critical.


    Notes:

    • Random is not a random number generator. It is a pseudo-random number generator. That means that if you know the initial state, the numbers generated are entirely predictable.
    • Using a true random seed for Random doesn't really help. It just makes the problem harder to reproduce.
    • There are likely to be other seeds for Random that will give you similar patterns with this particular test.
    • From a purely mathematical standpoint, ten ones is no more or less "random" than any other sequence of ten numbers. But from a mathematical perspective, Random is not random at all. In fact, it is totally predictable once you have figured out what the current value of N is. The problem is the auto-correlation that is making the sequence appear intuitively non-random.
    • If you want to avoid this kind of intuitive non-randomness, use SecureRandom which should either be a true random number source, or a generator of pseudo-random numbers that are much, much harder to predict.

提交回复
热议问题