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 }
原文地址:https://www.cnblogs.com/hapjin/p/5408880.html