【JAVA】產生隨機數:rand.nextInt(int n )


參考鏈接:

1. 代碼示例

  - `Random rand = new Random();`
  - `p += rand.nextInt(2); //取0-2(左閉右開不包括2)的整數`

2. rand.nextInt()的用法

  • 背景:

    • 自從JDK最初版本發布起,我們就可以使用java.util.Random類產生隨機數了。
    • 在JDK1.2中,Random類有了一個名為nextInt()的方法:public int nextInt(int n)
  • 給定一個參數n,nextInt(n)將返回一個大於等於0小於n的隨機數,即:0 <= nextInt(n) < n。

  • 源碼:

    /**
     * Returns a pseudo-random uniformly distributed {@code int}
     * in the half-open range [0, n).
     */
    public int nextInt(int n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n <= 0: " + n);
        }
        if ((n & -n) == n) {
            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;
    }
    

3. rand.nextInt隨機數取值范圍

  • 左閉右閉 [a,b]:rand.nextInt(b-a+1)+a

  • 左閉右開 [a,b):rand.nextInt(b-a)+a

  • 示例:

    • 要求在10到300中產生隨機數[10,300]包含10和300: int randNum = rand.nextInt(300-10+1) + 10;
    • rand.nextInt(300-10+1)=rand.nextInt(291)意思是產生[0,291)不包括291再加10就是[10,301)不包括301,如果要包括300所以要 rand.nextInt(300-10+1)里面要加1.
    • 如果是[10,300)不包括300就是 rand.nextInt(300-10)+10,不要加1.

4. random.nextInt()與Math.random()基礎用法

  • 1、來源

    • random.nextInt() 為 java.util.Random類中的方法;
    • Math.random() 為 java.lang.Math 類中的靜態方法。
  • 2、用法

    • 產生0-n的偽隨機數(偽隨機數參看最后注解):
    • // 兩種生成對象方式:帶種子和不帶種子(兩種方式的區別見注解)
      • Random random = new Random();

      • Integer res = random.nextInt(n);

      • Integer res = (int)(Math.random() * n);

  • 3、總結

    • Math.random() 方法生成[0, 1)范圍內的double類型隨機數;Random類中的nextXxxx系列方法生成0-n的隨機數;
    • Math.random() 線程安全,多線程環境能被調用;
    • 如無特殊需求,則使用(int)(Math.random()*n)的方式生成隨機數即可。
  • 4、注:何謂偽隨機數

    • 偽隨機既有規則的隨機,Random類中的隨機算法就是偽隨機。
    • 具體表現為:相同種子數的Random對象生成的隨機數序列相同:

END


免責聲明!

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



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