简体   繁体   English

创建 Random 类的对象或使用 Math.random() 以生成随机数

[英]Creating an object of Random class or using Math.random() in order to generate random numbers

When you have imported java.util.Random, you can both generate random integers and random double two ways.导入 java.util.Random 后,您可以通过两种方式生成随机整数和随机双精度数。

You could create an instance of the Random class您可以创建 Random 类的实例

Random randomGenerator = new Random();

and then use it to generate a random integer or double that is greater than or equal to 0 but less than 10然后用它生成一个大于或等于0但小于10的随机整数或双精度数

int randomInteger = randomGenerator.nextInt(10);
double randomDouble = randomGenerator.nextDouble(10);

You can also use Math.random()你也可以使用 Math.random()

int randomInteger = (int)(Math.random() * 10)
double randomDouble = Math.random() * 10

I think both methods gives the exact same result.我认为这两种方法都给出了完全相同的结果。 Is one of these two methods ever preferred rather than the other?这两种方法中的一种是否比另一种更受欢迎?

Math.random() uses the Random class. Math.random() 使用 Random 类。 And it's basically calling nextDouble() on the Random object of the Math class.它基本上是在 Math 类的 Random 对象上调用 nextDouble() 。

However the first method is definitely easier to understand and use.然而,第一种方法肯定更容易理解和使用。 And has more options then the Math class has.并且有比 Math 类更多的选择。 So I'd go with the Random class if you need a lot of Random numbers or if you need types other then double.因此,如果您需要大量随机数或者需要双精度以外的类型,我会选择 Random 类。 And I'd use Math.random() when you only need a double between 0 and 1.当您只需要 0 和 1 之间的双精度值时,我会使用 Math.random()。

So basically there is no difference in how the methods work, they both use the Random class.所以基本上方法的工作方式没有区别,它们都使用 Random 类。 So wich of the two you use depends on the situation as I stated above.因此,您使用的两者中的哪一个取决于我上面所说的情况。

From the javadoc for the Math class on the random method:从关于随机方法的 Math 类的 javadoc :

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression当这个方法第一次被调用时,它会创建一个新的伪随机数生成器,就像表达式一样

new java.util.Random()新的 java.util.Random()

Link to the javadoc page on Math.random(): https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()链接到 Math.random() 上的 javadoc 页面: https : //docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

I hope this helps :)我希望这有帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM