[Java] 產生亂數整數的方法

在 Java 中產生亂數有幾種方法,一般人最常用的就是 Math.random() 這個method,這個函式就是回傳一個正的double數值,他是介於 0.0~1.0 之間,但不包含 1.0的值。聰明的你一定想得到,如果我們要產生一個 1~42 的亂數,該怎樣做呢?答案其實很簡單,因為 Math.random()是回傳0.0~1.0之間的值,所以我們可以把 Math.random() 乘以42後,即會變成 0.0~42.0 的值,但不包含 42,再強制轉換成 int 型態後,再加上 1 即可。

用程式碼來說明,即是下列程式碼:

(int)(Math.random()*42+1)

 

第二種方法是使用 Random 這個 Class,以亂數產生整數而言,裡面有兩個函式,分別如下:

public int nextInt(int n)
public int nextInt()

 

就 nextInt(int n) 的原始碼如下:

public int nextInt(int n) {
   if (n <= 0)
     throw new IllegalArgumentException("n must be positive");

   if ((n & -n) == n)  // i.e., n is a power of 2
     return (int)((n * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % n;
   } while (bits - val + (n-1) < 0);
   return val;
 }

 

nextInt() 的原始碼如下:

public int nextInt()
{
    return next(32);
}

 

舉例來說,如果要產生 1~100 的值,我們則可以使用 nextInt(int n) 這個函式,寫法如下:

Random r=new Random();
System.out.println(r.nextInt(100));

 

但如果要產生 0~232 的亂數,則必須要使用 nextInt() 了。

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments