On Mon, 28 Jun 2021 15:57:21 GMT, Jim Laskey <[email protected]> wrote:
>> src/java.base/share/classes/java/util/random/RandomGenerator.java line 648:
>>
>>> 646: * power of two then limiting is a simple masking operation.
>>> Otherwise, a
>>> 647: * new result is re-calculated by averaging the previous result and
>>> 648: * {@code nextInt()} until the final result is greater equal zero
>>> and less
>>
>> I don't see how 'averaging' comes from the invocation of boundedNextInt
>> which appears to choose the first candidate that meets the criteria.
>> The comment also applies to nextLong overloads.
>
> If the first value calculated doesn't meet the criteria, then you either mask
> (power of 2) or go into this loop which does the averaging. The intent is not
> to bias the outcome.
>
>
> for (long u = r >>> 1; // ensure nonnegative
> u + m - (r = u % n) < 0L; // rejection check
> u = rng.nextLong() >>> 1) // retry
> ;
Yea you're right. I was focused on the divide by two, which appears to be to
just remove the sign. Clearer interpretation:
r = rng.nextLong();
n = range;
m = n - 1; // mask
for (long u = r / 2; // ensure nonnegative
u + m < r; // rejection check
u = rng.nextLong() / 2) // retry
r = u % n;
-------------
PR: https://git.openjdk.java.net/jdk17/pull/151