java.uti.Random類nextInt方法中隨機數種子為47的奇怪問題


一,問題描述

需要生成一個[0,1]的隨機數。即隨機生成 0 或者 1。使用java.util.Random類的 nextInt(int)方法,當構造Random類的對象並提供隨機數種子時,發現了一個奇怪的問題:

當使用 47 作為隨機數種子構造 Random對象時:

public static Random rand2 = new Random(47);
.....
System.out.println(rand2.nextInt(2));
.....

使用該對象調用 nextInt(2)方法,在Eclipse中測試,運行了20次,全部都生成 1,沒有出現一次0。

 

當不提供隨機數種子構造Random對象時:

public static Random rand = new Random();
.....
System.out.println(rand.nextInt(2));//0 or 1

在Eclipse中測試,運行了15次,10次出現0,5次出現1。

 

感覺,使用47做隨機數種子,且只需隨機 生成 0 和 1 這兩個數時,並不適合。

因為,測試了多次,它總是偏向於生成其中某一個數,而另一個數沒有出現。

 

 1 public class TestRand {
 2     public static Random rand = new Random();
 3     
 4     public static Random rand2 = new Random(47);
 5     
 6     public static void main(String[] args) {
 7         
 8         //System.out.println(rand.nextInt(2));//0 or 1
 9         //System.out.println(myRand(0,1));// 0 or 1
10         
11         System.out.println(rand2.nextInt(2));//always 1 or always 0
12         //System.out.println(myRand2(0, 1));//always 1 or always 0
13         
14     }
15     
16     public static int myRand(int i, int j){
17         return rand.nextInt(j - i + 1) + i;
18     }
19     
20     public static int myRand2(int i, int j){
21         return rand2.nextInt(j - i + 1) + i;
22     }
23 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM