math.random() follows which algorithms

前端 未结 5 1568
盖世英雄少女心
盖世英雄少女心 2021-01-03 03:47

Am using math.random() method to generate random numbers. but i had a doubt about that method. math.random() is which algorithms will fallow to generate random

5条回答
  •  感动是毒
    2021-01-03 04:38

    Java mainly provides four random number generator API's depending of your use case.

    java.lang.Math.random()

    If we check the Math class source code, we can view this:

    private static Random randomNumberGenerator;
    
    private static synchronized void initRNG() {
        if (randomNumberGenerator == null)
            randomNumberGenerator = new Random();
    }
    
    public static double random() {
        if (randomNumberGenerator == null) initRNG();
        return randomNumberGenerator.nextDouble();
    }
    

    Math.random() is simply a shortcut to call Random Class. It is more simple and less complete than java.util.Random but it's enough in some cases.

    java.util.Random

    The Random class implement a Linear Congruential Generator.

    LCG is a pretty simple formula for Pseudorandom Number Generation. java.util.Random is not trully random, it is totally deterministric. With the same initial condition (also called the seed), you've got the same result in the same order.

    Use java.util.Random is good for the most use cases (simulation, games, ...) but is not good for cryptography because of his predictability, for this kind of use case prefer java.security.SecureRandom.

    java.util.Random is thread safe but can have performance issues in multi-threaded context. If you work in a multi-threaded application, prefer ThreadLocalRandom.

    java.security.SecureRandom

    The SecureRandom class extend java.util.Random class to implement a cryptographically strong random number generator based on an entropy source. SecureRandom is not deterministic.

    SecureRandom have multiple implementation in function of your platform (the complete implementation list).

    java.security.SecureRandom is less fast than java.util.Random because of entropy source.

    java.util.concurrent.ThreadLocalRandom

    The ThreadLocalRandom class is another implementation of Linear Congruential Generator but this one isn't thread-safe but dedicated to a specific thread.

    This implementation is more fast than java.util.Random in multi-threaded context.


    In your case, you could use java.util.Collections.shuffle(list) to shuffle your array with java.util.Random or with a specific Random Generator like java.security.SecureRandom.

提交回复
热议问题