Today I suddenly remembered that Java produces random numbers. I tried it on the computer and found a little difference. I will summarize it here;
Directly calling Math.random() is to generate a random number between [0, 1),
If
java.util.Random random=new Random();random.nextInt()
This produces a long integer random number and is the same as the last time. If it is generated later, it will not be the same, for example:
for (int i = 0; i < 10; i++) { Random random=new Random(); Thread.sleep(100); System.out.print((int)random.nextInt(100)+" "); }It is to generate different random numbers
If you want to use java.util.Random() to generate random numbers in a specified range, you need to perform modulus calculations and perform some processing.
Random.nextInt(100) can also generate random numbers within 100. Generally, it is best to use nextInt (range). If it is not a large number of operations, you can use Math.random (because it can be slower to calculate and round it after floating point)
The above article briefly talks about the difference between Math.random() and java.util.random() in java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.