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

当前回答

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

例如:RandomDataGenerator.nextInt或RandomDataGenerator.nextLong

其他回答

让我们举个例子。

假设我希望生成5-10之间的数字:

int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);

让我们了解这一点。。。

用最高值初始化max,用最低值初始化min。现在,我们需要确定可以获得多少可能的值。在本例中,应为:5, 6, 7, 8, 9, 10所以,这个计数应该是max-min+1。即10-5+1=6随机数将生成0-5之间的数字。即0、1、2、3、4、5将最小值添加到随机数将产生:5, 6, 7, 8, 9, 10 因此,我们获得了所需的范围。

注意,该方法比下一个Int方法更偏向且效率更低,https://stackoverflow.com/a/738651/360211

实现这一点的一个标准模式是:

Min + (int)(Math.random() * ((Max - Min) + 1))

Java Math库函数Math.random()生成范围[0,1)内的双精度值。请注意,此范围不包括1。

为了首先获得特定的值范围,需要乘以要覆盖的值范围的大小。

Math.random() * ( Max - Min )

这将返回范围[0,Max Min)内的值,其中不包括“Max Min”。

例如,如果需要[5,10),则需要覆盖五个整数值,以便使用

Math.random() * 5

这将返回范围为[0.5)的值,其中不包括5。

现在,您需要将此范围移动到目标范围。您可以通过添加“最小值”值来实现此操作。

Min + (Math.random() * (Max - Min))

现在,您将获得范围为[Min,Max)的值。按照我们的示例,这意味着[5,10):

5 + (Math.random() * (10 - 5))

但是,这仍然不包括Max,您将得到双倍的值。为了获得包含的最大值,您需要向范围参数(Max-Min)添加1,然后通过强制转换为int来截断小数部分。这可以通过以下方式实现:

Min + (int)(Math.random() * ((Max - Min) + 1))

在[Min,Max]范围内的随机整数值,或者按照示例[5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))

Java中的Math.Random类是基于0的。所以,如果你这样写:

Random rand = new Random();
int x = rand.nextInt(10);

x将介于0-9之间(含0-9)。

因此,给定以下25项的数组,生成0(数组的基数)和array.length之间的随机数的代码为:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.nextInt( i.length );

由于i.length将返回25,因此nextInt(i.length)将返回0-24之间的数字。另一个选项是Math.Random,其工作方式相同。

index = (int) Math.floor(Math.random() * i.length);

为了更好地理解,请查看论坛帖子Random Intervals(archive.org)。

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

例如:RandomDataGenerator.nextInt或RandomDataGenerator.nextLong

我发现这个例子生成随机数:


此示例生成特定范围内的随机整数。

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {

  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }

    log("Done.");
  }

  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }

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

此类的示例运行:

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.