如何在特定范围内生成随机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`.

当前回答

我的一个朋友今天在大学里问过我同样的问题(他的要求是生成一个介于1和-1之间的随机数)。所以我写了这个,到目前为止,它在我的测试中运行良好。理想情况下,有很多方法可以在给定范围内生成随机数。试试看:

功能:

private static float getRandomNumberBetween(float numberOne, float numberTwo) throws Exception{

    if (numberOne == numberTwo){
        throw new Exception("Both the numbers can not be equal");
    }

    float rand = (float) Math.random();
    float highRange = Math.max(numberOne, numberTwo);
    float lowRange = Math.min(numberOne, numberTwo);

    float lowRand = (float) Math.floor(rand-1);
    float highRand = (float) Math.ceil(rand+1);

    float genRand = (highRange-lowRange)*((rand-lowRand)/(highRand-lowRand))+lowRange;

    return genRand;
}

执行方式如下:

System.out.println( getRandomNumberBetween(1,-1));

其他回答

有一个图书馆在https://sourceforge.net/projects/stochunit/用于处理范围的选择。

StochIntegerSelector randomIntegerSelector = new StochIntegerSelector();
randomIntegerSelector.setMin(-1);
randomIntegerSelector.setMax(1);
Integer selectInteger = randomIntegerSelector.selectInteger();

它具有边缘包含/排除。

我的一个朋友今天在大学里问过我同样的问题(他的要求是生成一个介于1和-1之间的随机数)。所以我写了这个,到目前为止,它在我的测试中运行良好。理想情况下,有很多方法可以在给定范围内生成随机数。试试看:

功能:

private static float getRandomNumberBetween(float numberOne, float numberTwo) throws Exception{

    if (numberOne == numberTwo){
        throw new Exception("Both the numbers can not be equal");
    }

    float rand = (float) Math.random();
    float highRange = Math.max(numberOne, numberTwo);
    float lowRange = Math.min(numberOne, numberTwo);

    float lowRand = (float) Math.floor(rand-1);
    float highRand = (float) Math.ceil(rand+1);

    float genRand = (highRange-lowRange)*((rand-lowRand)/(highRand-lowRand))+lowRange;

    return genRand;
}

执行方式如下:

System.out.println( getRandomNumberBetween(1,-1));

Use:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

整数x现在是可能结果为5-10的随机数。

import java.util.Random; 

public class RandomUtil {
    // Declare as class variable so that it is not re-seeded every call
    private static Random random = new Random();

    /**
     * Returns a psuedo-random number between min and max (both inclusive)
     * @param min Minimim value
     * @param max Maximim value. Must be greater than min.
     * @return Integer between min and max (both inclusive)
     * @see java.util.Random#nextInt(int)
     */
    public static int nextInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return random.nextInt((max - min) + 1) + min;
    }
}

我想知道Apache Commons Math库提供的任何随机数生成方法是否符合要求。

例如:RandomDataGenerator.nextInt或RandomDataGenerator.nextLong