Math.random () generates a pseudo random number between [0, 1]. Note left and right .
1. The first range, also the most commonly used use, [min, Max], are closed intervals.
For convenience we lift two numbers, [2, 8] between
0____1_____2_____3____4____5____6___7____8_____9____10
1 if we use Math.floor to approximate, we can look like this, take 2 as an example,
The numbers from 2 to 3 range are 2, for example 2.0001, 2.67, 2.9999. If you take 8 as an example,
8.1,8.999 also belong to 8. So we can launch,
Math.floor (Math.random () * (8-2 + 1) + 2);
Since it is rounding down, our step size should need to be plus 1 to get to the number 8 to 9, not including 9
General:
Math.floor (Math.random () * (Max-min + 1) + min)
Let's write a test function to simply verify that the average distribution is met
function random (CNT) {/
*
@cnt: [number], need to test the Times
* *
var random;
var result = {};
for (var i=0 i<cnt; ++i) {
random = Math.floor (Math.random () * (8-2 + 1) + 2);
if (random in result) {
result[random]++;
} else {
result[random] = 1;
}
} Console.log (result);
return result;
}
Random (100000);
Test results:
{2:14,395, 3:13,985, 4:14,519, 5:14,425, 6:14,248, 7:14,162, 8:14,266}
is obviously in line with the average distribution.
2) Math.ceil () to simulate,
Math.ceil (Math.random () * (Max-min + 1) + min-1)
3) Math.Round to simulate,
Math.Round (Math.random () * (Max-min + 1) + min-0.5)
2. The other ranges are similar and are not mentioned. Interested in can practice more