Today, a friend asked me: How JavaScript generates a specified range of numerical random numbers. Math.random () This method is believed to be known to generate random numbers. However, the general reference manual does not show how to use this method to generate random numbers within a specified range. This time I'll give you a detailed introduction to Math.random () and how to use it to generate random numbers within the scope of the development.
W3school's random () tutorial
Definitions and usage
The random () method can return a random number between 0 ~ 1.
Grammar
Math.random ()
return value
A pseudo random number between 0.0 ~ 1.0.
Instance
In this case, we'll get a random number between 0 and 1:
<script type= "Text/javascript" >
document.write (Math.random ());
</script>
//output:
0.15246391076246546
How to generate a random number for a specified range value
After reading the W3school tutorial, you should know the basic usage of the Math.random () method.
Rounding with parseint (), Math.floor () or Math.ceil ()
We see that the direct use of the Math.random () method produces a number less than 1, so:
Math.random () *5
The result is a random number less than 5. And what we usually want is an integer between 0-5, so we need to round up the resulting results and get the integers we expect. parseint (), Math.floor () and Math.ceil () can all be rounded up.
var randomnum = Math.random () *5;
alert (randomnum); 2.9045290905811183
alert (parseint (randomnum,10));//2
alert (Math.floor (Randomnum));//2
alert ( Math.ceil (Randomnum)); 3
As we can see from the test code, the effect of the parseint () and Math.floor () is the same, and all the parts of the integer are taken down. So parseint (Math.random () *5,10) and Math.floor (Math.random () *5) are random numbers between 0-4 generated, Math.ceil (Math.random () *5) is the number of random numbers between 1-5 generated.
Generate a specified range of numeric random numbers
So, if you want to generate random numbers of 1 to any value, the formula is this:
Max-Desired Maximum value
parseint (Math.random () *max,10) +1;
Math.floor (Math.random () *max) +1;
Math.ceil (Math.random () *max);
If you want to generate random numbers of 0 to any value, the formula is this:
Max-expected maximum value
parseint (Math.random () * (max+1), ten);
Math.floor (Math.random () * (max+1));
If you want to generate random numbers of arbitrary values to any value, the formula is this:
//MAX-expected maximum
/min-Expected minimum value
parseint (Math.random () * (max-min+1) +min,10);
Math.floor (Math.random () * (max-min+1) +min);
Read this article is not a lot of ah, for random number of math random use is not clear, I hope this article can bring you help, thank you!