Mathématique.random() explication
C'est une question Java assez simple (bien que probablement applicable à toute la programmation):
Math.random()
renvoie un nombre entre zéro et un.
Si je veux retourner un entier entre zéro et cent, je ferais:
(int) Math.floor(Math.random() * 101)
Entre un et cent, je ferais:
(int) Math.ceil(Math.random() * 100)
Mais si je voulais obtenir un nombre entre trois et cinq? Sera-ce comme la déclaration suivante:
(int) Math.random() * 5 + 3
Je connais nextInt()
dans java.lang.util.Random
. Mais je veux apprendre comment faire ceci avec Math.random()
.
5 answers
int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Sortie de randomWithRange(2, 5)
10 fois:
5
2
3
3
2
4
4
4
5
4
Les limites sont inclusive, c'est à dire [2,5] et min
doit être inférieur à max
dans l'exemple ci-dessus.
EDIT: Si quelqu'un allait essayer d'être stupide, et l'inverse min
et max
, vous pouvez changer le code:
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: Pour votre question sur double
s, c'est juste:
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
Et encore une fois si vous voulez à l'épreuve des idiots, c'est juste:
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}
Si vous voulez générer un nombre de 0 à 100, alors votre code ressemblerait à ceci:
(int)(Math.random() * 101);
Pour générer un nombre de 10 à 20 :
(int)(Math.random() * 11 + 10);
Dans le cas général:
(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
(où lowerbound
est inclus et upperbound
exclusif).
, L'inclusion ou l'exclusion de upperbound
dépend de votre choix.
Disons que range = (upperbound - lowerbound) + 1
alors upperbound
est inclusif, mais si range = (upperbound - lowerbound)
alors upperbound
est exclusif.
Exemple: Si je veux un entier entre 3-5, alors si range est (5-3)+1 alors 5 est inclus, mais si range est juste (5-3) alors 5 est exclusif.
Le Random
la classe de Java située dans le package java.util
servira mieux votre objectif. Il a quelques nextInt()
méthodes qui renvoient un entier. Celui qui prend un argument int générera un nombre entre 0 et cet int, ce dernier n'étant pas inclusif.
Voici une méthode qui reçoit des limites et renvoie un entier aléatoire. Il est légèrement plus avancé (complètement universel): les limites peuvent être à la fois positives et négatives, et les limites minimum/maximum peuvent venir dans n'importe quel ordre.
int myRand(int i_from, int i_to) {
return (int)(Math.random() * (Math.abs(i_from - i_to) + 1)) + Math.min(i_from, i_to);
}
En général, il trouve la distance absolue entre les bordures, obtient une valeur aléatoire pertinente, puis décale la réponse en fonction de la bordure inférieure.
Pour générer un nombre compris entre 10 et 20 inclus, vous pouvez utiliser java.util.Random
int myNumber = new Random().nextInt(11) + 10