Java产生随机数

前言:

  每一门程序设计语言基本都具有一个随机函数,而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     @Test
19     public void testRandom1() {
20         System.out.println(System.currentTimeMillis());
21     }
22 
23     /*
24      * 采用Math类产生随机数,其返回浮点类型,区间为:[0,1)
25      */
26     @Test
27     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     @Test
36     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 }

 



posted @ 2015-08-09 20:01  Sea_Sky  阅读(2710)  评论(0编辑  收藏  举报

转载请注明出处! About me