Generation of the same sequence of random numbers

后端 未结 5 1893
广开言路
广开言路 2021-01-07 20:42

I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers,

5条回答
  •  难免孤独
    2021-01-07 21:19

    Math.random is just a wrapper of the class java.util.Random. The first time you call Math.random an instance of the class java.util.Random is created.

    Now, most API's don't expose any true random number generators, because they cannot be implemented in software. Instead, they use pseudo-random number generators, which generate a sequence of random-looking numbers using a bunch of formulas. This is what java.util.Random does. However, every pseudo-random number generator needs to be seeded first. If you have two pseudo-random number generators which use the same algorithm and use the same seed, they will produce the same output.

    By default, java.util.Random uses the milliseconds since January 1, 1970 as the seed. Therefore, everytime you start your program, it will produce different numbers (unless you manage it to start java up in under 1 millisecond). So, the solution to your problem is to create your own java.util.Random instance and seed it by yourself:

    import java.util.Random;
    
    class ... {
        Random randomNumberGenerator = new Random(199711);
    
        public void ...()
        {
            int randomInt = randomNumberGenerator.nextInt();
            double randomDouble = randomNumberGenerator.nextDouble();
        }
    }
    

    The randomNumberGenerator will always spit out the same sequence of numbers, as long as you don't change the seed(the 199711).

提交回复
热议问题