[ 
https://issues.apache.org/jira/browse/LANG-1592?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17161822#comment-17161822
 ] 

Alex Herbert commented on LANG-1592:
------------------------------------

This occurs as the method is using the {{nextDouble(double min, double max)}} 
method then casting back to a {{long}}.

A correct implementation would be to work only with the {{long}} datatype:

{code:java}
public static long nextLong(final long startInclusive, final long endExclusive) 
{
    Validate.isTrue(endExclusive >= startInclusive,
            "Start value must be smaller or equal to end value.");
    Validate.isTrue(startInclusive >= 0, "Both range values must be 
non-negative.");

    if (startInclusive == endExclusive) {
        return startInclusive;
    }

    return startInclusive + nextLong(endExclusive - startInclusive);
}

/**
 * Create a random long in the range 0 inclusive to {@code n} exclusive.
 *
 * @param n the upper limit (exclusive)
 * @return the long
 */
private static long nextLong(long n) {
    long bits;
    long val;
    do {
        bits = RANDOM.nextLong() >>> 1;
        val  = bits % n;
    } while (bits - val + (n - 1) < 0);

    return val;
}
{code}


> The random number generated by RandomUtils exceeds the exclusive parameter
> --------------------------------------------------------------------------
>
>                 Key: LANG-1592
>                 URL: https://issues.apache.org/jira/browse/LANG-1592
>             Project: Commons Lang
>          Issue Type: Bug
>          Components: lang.*
>    Affects Versions: 3.11
>            Reporter: huang pingcai
>            Priority: Minor
>         Attachments: image-2020-07-21-14-35-27-870.png
>
>
> {code:java}
> @Test
> public void test() {
>     while (RandomUtils.nextLong(12900000000001L, 12900000000016L) != 
> 12900000000016L) {
>     }
>     System.out.println("should not be invoked");
> }
> {code}
> !image-2020-07-21-14-35-27-870.png|width=315,height=182!



--
This message was sent by Atlassian Jira
(v8.3.4#803005)

Reply via email to