In scenarios where generating arbitrarily large random integers within a specified range is necessary, a common approach might involve using nextDouble() and multiplying the output by the desired limit. However, this method becomes problematic for values exceeding 2^53, leading to non-uniform distribution.
To overcome this limitation, Java provides the BigInteger class, which offers a constructor that generates random numbers uniformly distributed between 0 and (2^numBits - 1), inclusive.
To generate a random value in the range 0 to n, where n is not a power of 2, a simple loop can be employed:
<code class="java">BigInteger randomNumber; do { randomNumber = new BigInteger(upperLimit.bitLength(), randomSource); } while (randomNumber.compareTo(upperLimit) >= 0);</code>
This iterative approach ensures a uniform distribution within the desired range. Typically, only one or two iterations are required.
For scenarios where the random number generator is computationally expensive, the number of iterations in the loop can be restricted as follows:
<code class="java">int nlen = upperLimit.bitLength(); BigInteger nm1 = upperLimit.subtract(BigInteger.ONE); BigInteger randomNumber, temp; do { temp = new BigInteger(nlen + 100, randomSource); randomNumber = temp.mod(upperLimit); } while (s.subtract(randomNumber).add(nm1).bitLength() >= nlen + 100);</code>
This modified version is highly unlikely to require multiple iterations (probability less than 2^100). However, it incurs a computational penalty due to the mod() operation. Thus, it is recommended only if the random number generator is particularly slow.
The above is the detailed content of ## How do you generate random BigInteger values within a specific range in Java?. For more information, please follow other related articles on the PHP Chinese website!