简体   繁体   中英

ThreadLocalRandom random integer not in range

I executed this bunch of code:

 int newOrderLow = ThreadLocalRandom.current().nextInt(50, shipCapacity / 3); int newOrderUp = ThreadLocalRandom.current().nextInt(newOrderLow, shipCapacity + 1); // not lower than lower value int newOrderMid = ThreadLocalRandom.current().nextInt(newOrderLow, newOrderUp + 1); // in between Log.d(TAG, "New Order: {" + newOrderLow + ", " + newOrderMid + ", " + newOrderUp + "}"); 

and started debugging it. For example, when I set shipCapacity as 600, I got these figures logged in my console:

 New Order: {493, 772, 672} 

One thing is that upper range is not within [lower value; shipCapacity + 1], the other one is the middle value result. So what is the issue? How to generate random integers properly using ThreadLocalRandom?

You might want to consider running following test code:

    @Test
    public void test1() {
        final int shipCapacity = 600;
        for (int i = 0; i < 1000000; i++) {
            int newOrderLow = ThreadLocalRandom.current().nextInt(50, shipCapacity / 3);
            int newOrderUp = ThreadLocalRandom.current().nextInt(newOrderLow, shipCapacity + 1); // not lower than lower value
            int newOrderMid = ThreadLocalRandom.current().nextInt(newOrderLow, newOrderUp + 1); // in between

            System.out.println("numbers= " + newOrderLow + " " + newOrderUp + " " + newOrderMid);
            assertThat(newOrderLow).isBetween(50, shipCapacity / 3);
            assertThat(newOrderUp).isBetween(newOrderLow, shipCapacity + 1);
            assertThat(newOrderMid).isBetween(newOrderLow, newOrderUp + 1);
    }

I've done that and on my machine none of the rules that you mentioned seem to be violated.

In my opinion the problem is somewhere else, not in the code that you provided, but test it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM