Math.random()
Returns one between 0 (inclusive) and 1 (not included) Number
. so we have an interval like this:
Now, we want a min
number between (contained) and max
(not included):
[0 ... ... 1] [Min.................................max] (......).................... (): [+])
First, however, we should subtract from the second interval min
to adjust the problem:
[0....................................1] [Min-min ... max-min. .........].-----)
This gives the following:
[0 ... ... 1] [0....................................max-min] (......).................... (): [+])
We can now apply Math.random
and then calculate. Let's choose a random number:
Math.random () | [0 ..... ..... ..... ..... ..... ........ ..... 1) [0 ... .... max-min .....................]
Therefore, we need:
x = Math.random () * (max-min);
Don't forget min
to add, so we get a number in [Min,max]:
x = Math.random () * (max-min) + min;
The second, the return min
and max
the integer between, both are contained.
Now, in order to get an integer, you can use round
, ceil
or floor
.
You can use Math.round(Math.random() * (max - min)) + min
However, it is possible that the range I want is [2, 5), then Math.random () * (max-min) comes out with a maximum value of 4.6, but Math.Round () rounding becomes the maximum value of 5.
So, use Math.floor (Math.random () * (max-min)) + min
Turn from
http://blog.leanote.com/post/dujuncheng/%E5%9C%A8Javascript%E5%9C%A8%E7%89%B9%E5%AE%9A%E8%8C%83%E5%9B%B4%E7%94 %9f%e6%88%90%e9%9a%8f%e6%9c%ba%e6%95%b0%ef%bc%9f
Generate random numbers at a specific range in JavaScript