更新時(shí)間:2022-12-15 11:11:35 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1528次
通常情況下,我們會(huì)提出生成隨機(jī)數(shù)或生成范圍內(nèi)隨機(jī)數(shù)的 2 類需求。Java 支持通過ThreadLocalRandom, java.lang.Math和java.util.Random類生成隨機(jī)數(shù)。讓我們看看有哪些不同的選項(xiàng)以及如何在Java生成隨機(jī)數(shù)。
如果您使用的是 Java 1.7 或更高版本,ThreadLocalRandom應(yīng)該是您在 Java 中生成隨機(jī)數(shù)的標(biāo)準(zhǔn)方法。在 Java 或任何其他語言中生成隨機(jī)數(shù)時(shí)可以有 2 種變體。
生成沒有范圍的隨機(jī)數(shù)。
生成給定范圍內(nèi)的隨機(jī)數(shù)。
package com.javadevjournal.date;
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumberGeneration {
public static void main(String[] args) {
int lowerBound = 4;
int upperBound = 20;
int random_int = ThreadLocalRandom.current().nextInt(); //returns pseudorandom value
System.out.println(random_int); //output will be different on different machine (2063277431 while running example);
/*generate random int within given range between 0 upper given bound.
* The upper bound is non exclusive i'e it will not be counted while generating the
* random number.
* */
int random_int_with_upper_bound = ThreadLocalRandom.current().nextInt(upperBound);
System.out.println(random_int_with_upper_bound); // 6 while we were running the code.
/**
* Generate random number with a given range of lower and upper bound.
*/
int random_int_range = ThreadLocalRandom.current().nextInt(lowerBound, upperBound + 1);
System.out.println(random_int_range); // 18 while we were running the code.
}
}
使用時(shí)請(qǐng)記住以下要點(diǎn)ThreadLocalRandom。
如果您不提供下限,則下限為 0。
上限是非排他性的,如果要在隨機(jī)數(shù)生成中添加上限(將上限加 1 以包含它),則需要小心。
我們不需要對(duì)ThreadLocalRandom類進(jìn)行顯式初始化。
如果綁定是<=0,它將拋出IllegalArgumentException。
如果下限大于或等于上限,類將拋出IllegalArgumentException。
int lowerBound = 4;
int upperBound = 3;
/**
* These will throw IllegalArgumentException.
*/
ThreadLocalRandom.current().nextInt(lowerBound, upperBound);
ThreadLocalRandom.current().nextInt(0);
nextDouble()andnextFloat()方法允許生成 float 和 double 值。它的工作方式類似于上面的示例,我們可以在生成隨機(jī) double 或 float 數(shù)字時(shí)傳遞下限和上限。
ThreadLocalRandom.current().nextDouble();
ThreadLocalRandom.current().nextDouble(1.0, 34.0);
ThreadLocalRandom.current().nextFloat();
如果您使用的不是 Java 1.7 或更高版本,我們可以使用java.util.Random該類在 Java 中生成隨機(jī)數(shù)。以下是該類的一些詳細(xì)信息:
nextInt(upperBound) – Generate random int between 0 and upperbound -1;
nextFloat() – Generate float between 0.0 to 1.0.
nextDouble() – Generate double between 0.0 to 1.0.
package com.javadevjournal.date;
import java.util.Random;
public class RandomNumberGeneration {
public static void main(String[] args) {
int min = 1;
int max = 67;
Random random = new Random();
//Get random int between [0-66]
int randomInt = random.nextInt(max);
/*
If we want to include 67 in the range, add 1 to the upper bound
i.e max+1
generate random int between [0- 67]
*/
int upperBoundInt = random.nextInt(max + 1);
//another variation
int randomNum = random.nextInt((max - min) + 1) + min;
//Double random number
double randomDouble = random.nextDouble();
float randomFloat = random.nextFloat();
}
}
如果我們只需要整數(shù)或浮點(diǎn)隨機(jī)值,我們可以使用 Math.random。這是來自Math.random類的示例代碼:
double random = Math.random();
這將返回大于或等于0.0且小于的正雙精度值1.0。在許多用例中,我們可能希望在給定范圍內(nèi)生成隨機(jī)數(shù)。其中一種選擇是使用以下表達(dá)式
<前>Math.random() * ((max - min) + 1)) +min
Math.random()在范圍內(nèi)生成雙精度值 [0,1)。
要獲得特定范圍的值,我們應(yīng)該乘以我們想要覆蓋的值范圍的大小 ( * ( Max - Min ))。
將此范圍向上移動(dòng)到您的目標(biāo)范圍。您可以通過添加最小值(表達(dá)式的最后一部分+min)來做到這一點(diǎn)
public class RandomNumberGeneration {
public static void main(String[] args) {
double min = 1;
double max = 67;
/*
Generate random number with in given range
*/
double random = (int)(Math.random() * ((max - min) + 1));
System.out.println(random);
}
}
如果您只對(duì)將 int 作為隨機(jī)數(shù)感興趣,您應(yīng)該選擇 ,Random.nextInt(n)因?yàn)榇诉x項(xiàng)更有效且偏差更小。以下是使用Random.nextInt over的一些優(yōu)點(diǎn)Math.random()
Math.random()在內(nèi)部使用Random.nextDouble()。最好使用原始的而不是通過它進(jìn)行路由。
Random.nextInt(n)是可重復(fù)的。我們可以通過傳遞相同的種子來創(chuàng)建 2 個(gè)不同的隨機(jī)對(duì)象。
Math.random()也需要大約兩倍的處理,并且需要同步。
雖然大多數(shù)情況可以使用 輕松完成,但是,如果您對(duì)如何在 Java 8ThreadLocalRandom中生成隨機(jī)數(shù)更感興趣 ,這里有幾個(gè)選項(xiàng)可以使用Java 8完成它。
import java.util.Random;
import java.util.SplittableRandom;
import java.util.stream.IntStream;
public class RandomNumberGeneration {
public static void main(String[] args) {
int min = 1;
int max = 67;
int size=50;
/*
return int between the specified
* min range (inclusive) and the specified upper bound (exclusive).
*/
int randomInt= new SplittableRandom().nextInt(min, max);
//TO return stream of random values
IntStream stream = new SplittableRandom().ints(size, min, max);
// to generate int[]
int[] randomArray= new SplittableRandom().ints(size, min, max).toArray();
int[] randomArray1= new Random().ints(size, min,max).toArray();
}
}
以上就是關(guān)于“Java產(chǎn)生隨機(jī)數(shù)的方法”介紹,大家如果想了解更多相關(guān)知識(shí),不妨來關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java在線學(xué)習(xí),里面的課程內(nèi)容細(xì)致全面,很適合沒有基礎(chǔ)的小伙伴學(xué)習(xí),希望對(duì)大家能夠有所幫助。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743