一,問題描述
需要生成一個[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 }