3783 votes

Comment générer des nombres entiers aléatoires dans une plage spécifique en Java ?

Comment puis-je générer un échantillon aléatoire int dans une fourchette spécifique ?

J'ai essayé les éléments suivants, mais ils ne fonctionnent pas :

Tentative 1 :

randomNum = minimum + (int)(Math.random() * maximum);

Bug : randomNum peut être plus grande que maximum .

Tentative 2 :

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

Bug : randomNum peut être plus petite que minimum .

0 votes

Lorsque vous avez besoin d'un grand nombre de nombres aléatoires, je ne recommande pas la classe Random de l'API. Elle a juste une période trop petite. Essayez la classe Torsion de Mersenne au lieu de cela. Il y a une implémentation Java .

20 votes

Avant de poster une nouvelle réponse, pensez qu'il y a déjà plus de 65 réponses à cette question. Veillez à ce que votre réponse apporte des informations qui ne figurent pas parmi les réponses existantes.

0 votes

randomNum = minimum + (int)(Math.random() * (maximum - minimum);

17voto

gerardw Points 330

Une autre option est d'utiliser simplement Apache Commons :

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }

16voto

raupach Points 1443

Lorsque vous avez besoin d'un grand nombre de nombres aléatoires, je ne recommande pas la classe Random de l'API. Elle a juste une période trop petite. Essayez la classe Torsion de Mersenne au lieu de cela. Il y a une implémentation Java .

16voto

Hospes Points 51

J'ai trouvé cet exemple Générer des nombres aléatoires :


Cet exemple génère des nombres entiers aléatoires dans une plage spécifique.

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);
  }
} 

Un exemple d'exécution de cette classe :

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.

14voto

ganesh Points 11
rand.nextInt((max+1) - min) + min;

Cela fonctionne bien.

14voto

Yakiv Mospan Points 1291

Voici un exemple simple qui montre comment générer un nombre aléatoire à partir d'un fichier fermé. [min, max] tandis que min <= max is true

Vous pouvez le réutiliser comme champ dans une classe de trou, en ayant également tous les éléments suivants Random.class méthodes en un seul endroit

Exemple de résultats :

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

Sources :

import junit.framework.Assert;
import java.util.Random;

public class RandomUtils extends Random {

    /**
     * @param min generated value. Can't be > then max
     * @param max generated value
     * @return values in closed range [min, max].
     */
    public int nextInt(int min, int max) {
        Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
        if (min == max) {
            return max;
        }

        return nextInt(max - min + 1) + min;
    }
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X