Random
Math.random() fournit un nombre (float) au hasard dans l'intervalle [0;1[.
Math.random() fournit un nombre (float) au hasard dans l'intervalle [0;1[.
Pour tirer un nombre float au hasard dans l'intervalle [a;b[, il suffit d'utiliser l'instruction
(b-a) * Math.random() + a.
Si x est le résultat d'un Math.random(), on a : \( 0 \leqslant x < 1 \) ,
d'où \( 0 \leqslant x \times (b-a) < b-a \) et \( a \leqslant x \times (b-a) +a < b \).
Pour tirer au hasard un entier entre l'entier n et l'entier m (n et m compris, n < m), on utilisera l'instruction
n + Math.floor( (m-n +1) * Math.random() )
Si x est un résultat de Math.random(), on a \( 0 \leqslant x < 1\) et
\( 0 \leqslant (m-n+1) x < m-n+1\).
On prend ensuite la partie entière ( fonction notée \( \lfloor \ \rfloor \) ) du résultat : \[ \lfloor (m-n+1) x \rfloor \in \lbrace 0; 1; 2; 3; \dots; m-n \rbrace \] et l'on ajoute n : \[ n + \lfloor (m-n+1) x \rfloor \in \lbrace n; n+1; n+2; n+3; \dots; m \rbrace \]