如何在特定范围内生成随机int值?

以下方法存在与整数溢出相关的错误:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.

当前回答

我正在考虑使用以下方法将生成的随机数线性归一化到所需范围。设x为随机数,设a和b为期望归一化数的最小和最大范围。

下面是一个非常简单的代码片段,用来测试线性映射产生的范围。

public static void main(String[] args) {
    int a = 100;
    int b = 1000;
    int lowest = b;
    int highest = a;
    int count = 100000;
    Random random = new Random();
    for (int i = 0; i < count; i++) {
        int nextNumber = (int) ((Math.abs(random.nextDouble()) * (b - a))) + a;
        if (nextNumber < a || nextNumber > b) {
            System.err.println("number not in range :" + nextNumber);
        }
        else {
            System.out.println(nextNumber);
        }
        if (nextNumber < lowest) {
            lowest = nextNumber;
        }
        if (nextNumber > highest) {
            highest = nextNumber;
        }
    }
    System.out.println("Produced " + count + " numbers from " + lowest
            + " to " + highest);
}

其他回答

下面是一个函数,它按照用户42155的请求,在lowerBoundIncluded和upperBoundIncluded定义的范围内返回一个整数随机数

SplitableRandom splitableRandom=新的Splitablerandom();

BiFunction<Integer,Integer,Integer> randomInt = (lowerBoundIncluded, upperBoundIncluded)
    -> splittableRandom.nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

randomInt.apply(…,…);//获取随机数

…或更短,用于一次性生成随机数

new SplittableRandom().nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

以前的大多数建议都不考虑“溢出”。例如:min=整数.min_VALUE,max=100。到目前为止,我采用的正确方法之一是:

final long mod = max- min + 1L;
final int next = (int) (Math.abs(rand.nextLong() % mod) + min);

我认为这段代码会奏效。请尝试一下:

import java.util.Random;
public final class RandomNumber {

    public static final void main(String... aArgs) {
        log("Generating 10 random integers in range 1..10.");
        int START = 1;
        int END = 10;
        Random randomGenerator = new Random();
        for (int idx=1; idx<=10; ++idx) {

            // int randomInt=randomGenerator.nextInt(100);
            // log("Generated : " + randomInt);
            showRandomInteger(START,END,randomGenerator);
        }
        log("Done");
    }

    private static void log(String aMessage) {
        System.out.println(aMessage);
    }

    private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        long range = (long)aEnd - (long)aStart + 1;
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int) (fraction + aStart);
        log("Generated" + randomNumber);
    }
}

可以使用以下代码:

ThreadLocalRandom.current().nextInt(rangeStart, rangeEndExclusive)
rand.nextInt((max+1) - min) + min;

这很好。