First, the preparatory knowledge
Math.ceil (); To take the whole up.
Math.floor ()///down rounding.
Math.Round ();//rounded.
Math.random (); a pseudo-random number between//0.0 ~ 1.0. "Contains 0 does not contain 1"//such as 0.8647578968666494
Math.ceil (Math.random () *10); Gets a random integer from 1 to 10, and the probability of taking 0 is minimal.
Math.Round (Math.random ()); A random integer of 0 to 1 can be obtained evenly.
Math.floor (Math.random () *10);//To obtain a balanced 0 to 9 random integer.
Math.Round (Math.random () *10);//Basic equalization gets a random integer from 0 to 10, where the probability of getting a minimum value of 0 and a maximum of 10 is less than half.
Because the result in 0~0.4 is 0, 0.5 to 1.4 1 ... 8.5 to 9.4 is 9, 9.5 to 9.9 is 10. So the distribution between the ends is only half the number of other digits.
Second, generate [n,m] random integer
function function: A random integer that generates [N,m].
It is useful when JS generates a CAPTCHA or randomly selects an option.
Generates random number
function Randomnum (minnum,maxnum) {
switch (arguments.length) {Case 1) from Minnum to Maxnum
:
Return parseint (Math.random () *minnum+1,10);
break;
Case 2: Return
parseint (Math.random () * (maxnum-minnum+1) +minnum,10);
break;
Default: Return
0;
break;
}
}
Process Analysis:
Math.random () generates the number of [0,1], so the number of math.random () *5 generate {0,5).
You usually expect to get integers, so you have to deal with the results.
parseint (), Math.floor (), Math.ceil () and Math.Round () can all get integers.
The parseint () and Math.floor () results are rounded down.
So Math.random () *5 generates all of the random integers [0,4].
So the random number of [1,max] is generated, and the formula is as follows:
Max-Desired Maximum value
parseint (Math.random () *max,10) +1;
Math.floor (Math.random () *max) +1;
Math.ceil (Math.random () *max);
So the random number of [0,max] to any number is generated, and the formula is as follows:
Max-expected maximum value
parseint (Math.random () * (max+1), ten);
Math.floor (Math.random () * (max+1));
So you want to generate a random number for [Min,max], the formula is as follows:
Max-expected maximum
/min-Expected minimum value
parseint (Math.random () * (max-min+1) +min,10);
Math.floor (Math.random () * (max-min+1) +min);
The above is about JS generation random number of comprehensive analysis, very meticulous, hope can help everyone.