原文:Java Random Number Generator – How to Generate Integers With Math Random,作者:Thanoshan MV
计算机生成的随机数分为两类:真随机数和伪随机数。
真随机数是根据外部因素生成的。例如,利用周围的噪音产生随机性。
但生成这样的真随机数是一项耗时的任务。因此,我们可以利用伪随机数,它是用一种算法和一个种子值生成的。
这些伪随机数足以满足大多数目的。例如,你可以在密码学中使用它们,在构建骰子或纸牌等游戏中使用它们,以及在生成OTP(一次性密码)时使用它们。
在这篇文章中,我们将学习如何在 Java 中使用 Math.random()
生成伪随机数。
使用 Math.random() 生成整数
Math.random()
返回一个伪随机数,大于或等于 0,且小于 1。
让我们用一些代码来试试吧。
public static void main(String[] args) {
double randomNumber = Math.random();
System.out.println(randomNumber);
}
// 输出 #1 = 0.5600740702032417
// 输出 #2 = 0.04906751303932033
randomNumber
会在每次执行时给我们一个不同的随机数。
比方说,我们想在一个指定的范围内生成随机数,例如,0 到 4。
// 生成 0 到 4 之间的随机数
public static void main(String[] args) {
// Math.random() 生成 0.0 到 0.999 之间的随机数
// 那么,Math.random()*5 的范围是 0.0 到 4.999
double doubleRandomNumber = Math.random() * 5;
System.out.println("doubleRandomNumber = " + doubleRandomNumber);
// 将浮点型数转为整数
int randomNumber = (int)doubleRandomNumber;
System.out.println("randomNumber = " + randomNumber);
}
/* Output #1
doubleRandomNumber = 2.431392914284627
randomNumber = 2
*/
当我们将一个浮点型数转换为 int 时,int 值只保留整数部分。
例如,在上面的代码中,doubleRandomNumber
是 2.431392914284627
。doubleRandomNumber
的整数部分是 2
,小数部分(小数点后的数字)是 431392914284627
。所以,randomNumber
只保留整数部分 2
。
你可以在 Java 文档中阅读更多关于 Math.random()
方法的内容。
使用 Math.random()
并不是在 Java 中生成随机数的唯一方法。接下来,我们将考虑如何使用 Random 类来生成随机数。
使用 Random 类来生成整数
在 Random 类中有许多实例方法可生成随机数。在本节中,我们将考虑两个实例方法,nextInt(int bound)
和 nextDouble()
。
如何使用 nextInt(int bound) 方法
nextInt(int bound)
返回一个 int 类型的伪随机数,大于或等于 0 且小于边界值。
bound
参数指定了范围。例如,如果我们指定边界为 4,nextInt(4)
将返回一个 int 类型的值,大于或等于 0,且小于 4。0、1、2、3 是 nextInt(4)
的可能结果。
由于这是一个实例方法,我们应该创建一个随机对象来访问这个方法。让我们来试试。
public static void main(String[] args) {
// 创建随机对象
Random random = new Random();
// 生成从 0 到 3 的随机数
int number = random.nextInt(4);
System.out.println(number);
}
如何使用 nextDouble() 方法
与 Math.random()
类似,nextDouble()
返回一个浮点类型的伪随机数,大于或等于 0,且小于 1。
public static void main(String[] args) {
// 创建随机对象
Random random = new Random();
// 生成从 0.0 到 1.0 的随机数
double number = random.nextDouble();
System.out.println(number);
}
你可以阅读 Random 类的 Java 文档,以了解更多信息。
那么你应该使用哪种随机数方法呢
Math.random() 使用 Random 类。如果我们在应用中只想得到浮点类型的伪随机数,那么我们可以使用 Math.random()
。
否则,我们可以使用 Random 类,因为它提供了各种方法来生成不同类型的伪随机数,如 nextInt()
、nextLong()
、nextFloat()
和 nextDouble()
。
谢谢你阅读本文。
照片来源:Unsplash,作者:Brett Jordan
你可以在 Medium 上与我联系。
Happy Coding!