標籤:
前言:
每一門程式設計語言基本都具有一個隨機函數,而Java當中產生隨機數的方式不拘一格。而且其中的Random工具類還有著更深入的應用,但本文僅對比3種產生隨機數的方式,就不深入擴充分析其內部工具類了。
1)System.currentMillis()函數返回基於目前時間的Long整型隨機數;
2)Math.random()返回0到1之間的浮點數,而且屬於左閉右開:[0,1);
3)通過New Random().nextInt()執行個體化對象並利用函數產生一個int類型的隨機數。
三種不同方式的代碼實現如下:
1 package random; 2 3 import java.util.Random; 4 5 import org.junit.Test; 6 7 public class RandomTest { 8 9 public static void main(String[] args) {10 new RandomTest().testRandom1();11 new RandomTest().testRandom2();12 new RandomTest().testRandom3();13 }14 15 /*16 * 根據當前的標準時間,返回單個long類型的隨機數17 */18 @Test19 public void testRandom1() {20 System.out.println(System.currentTimeMillis());21 }22 23 /*24 * 採用Math類產生隨機數,其返回浮點類型,區間為:[0,1)25 */26 @Test27 public void testRandom2() {28 for(int i=0;i<10;i++)29 System.out.println(Math.random());30 }31 32 /*33 * 利用Randoml工具類,產生10個隨機數 當種子seed一樣時,產生的2個序列相同34 */35 @Test36 public void testRandom3() {37 Random random1 = new Random(1);38 for (int i = 0; i < 10; i++) {39 System.out.print(random1.nextInt()+" ");40 }41 System.out.println();42 Random random2 = new Random(1);43 for (int i = 0; i < 10; i++) {44 System.out.print(random2.nextInt()+" ");45 }46 }47 }
另外,考慮到有些情況下我們需要批量產生隨機數,故寫了下面的程式。其功能是實現批量產生N個[0,MAX)範圍內的隨機數並寫入txt檔案:
1 package random; 2 3 import java.io.File; 4 import java.io.PrintWriter; 5 6 public class RandomFactory { 7 8 final static int N=1000000; //產生的隨機數的個數 9 final static int MAX=10000; // 產生隨機數的範圍:[0,MAX)10 final static String PATH="D:/random100w.txt"; //產生的檔案路徑11 public static void main(String[] args) throws Exception{12 13 PrintWriter output = new PrintWriter(new File(PATH));14 for(int i=0;i<N;i++){15 int x=(int)(Math.random()*1e4);16 output.println(x);17 }18 //記得關閉字元流19 if(output!=null){20 output.close();21 }22 System.out.println("--End--");23 }24 25 }
Java產生隨機數