Random.nextLong(long bound)?

Andrew Haley aph at redhat.com
Thu Oct 19 12:01:02 UTC 2017

On 18/10/17 22:54, Steven Schlansker wrote:

> Given a long L1 which can be generated and L2 which cannot, it seems
> trivial that P(L1) != P(L2) and therefore it is not a uniformly
> distributed long value.  Am I misunderstanding this concept?

I think it's OK.

The result of nextLong() is uniformly distributed over all 64 bits of
a long because nextLong() returns:

    ((long)(next(32)) << 32) + next(32)

To get your bounded long, you can use

    Math.multiplyHigh(r.nextLong(), bound)

Bear in mind that if you want a result bounded below at zero you'll
have to correct the sign.

Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671

More information about the core-libs-dev mailing list