[JAVA] generates a random number: rand.nextInt (int n)

Reference links:

1. Code Example

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

2. rand.nextInt () usage

  • background:

    • Since the initial release from the JDK, we can use a random number generated java.util.Random class.
    • In JDK1.2, Random have a class called the nextInt () method:public int nextInt(int n)
  • Given a parameter n, the nextInt (n) returns a random number greater than or equal to 0 less than n, namely: 0 <= nextInt (n) <n. 

  • Source:

    /**
     * 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 random number range

  • Closing the left and right closed [a, b]:rand.nextInt(b-a+1)+a

  • Left and right open and closed [a, b):rand.nextInt(b-a)+a

  • Example:

    • Generating a random number required in the 10 to 300 [10,300] comprising 10 and 300: int randNum = rand.nextInt(300-10+1) + 10;
    • rand.nextInt (300-10 + 1) = rand.nextInt (291) generating means [0,291) that does not include the 291 plus 10 [10,301) 301 is not included, if so to include 300 rand.nextInt (300-10 +1) inside to add 1.
    • If you are [10, 300) does not include the 300 is rand.nextInt (300-10) +10, do not incremented.

4. random.nextInt () and Math.random () Basic usage

  • 1 source

    • random.nextInt () method of class java.util.Random;
    • Math.random () is a static method java.lang.Math class.
  • 2, usage

    • Generates a pseudo-random number (pseudo-random number with reference to the last comment) 0-n of:
    • // two ways to generate objects: with seeds and without seeds (see note the difference between the two approaches)
      • Random random = new Random();
      • Integer res = random.nextInt(n);

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

  • 3, summary

    • Math.random () method to generate [0, 1) double type in the range of random numbers; nextXxxx Series Method Random class 0-n generated random number;
    • Math.random () thread-safe, multi-threaded environment can be called;
    • If no special requirement, using (int) (Math.random () * n) to generate a random number manner.
  • 4, note: what pseudo-random number

    • Pseudorandom existing rules of random, random algorithm Random class is pseudo-random.
    • Specific performance: the same number of the same seed Random object generated random number sequence:

END

Guess you like

Origin www.cnblogs.com/anliux/p/12327584.html