May 09, 2021 CoffeeScript
You need to generate random numbers in a certain range.
Use JavaScript's Math.random() to get floating-point numbers to satisfy 0-lt;X-lt;1.0. Use multiplication and Math.floor to get numbers in a certain range.
probability = Math.random()
0.0 <= probability < 1.0
# => true
# 注意百分位数不会达到 100。从 0 到 100 的范围实际上是 101 的跨度。
percentile = Math.floor(Math.random() * 100)
0 <= percentile < 100
# => true
dice = Math.floor(Math.random() * 6) + 1
1 <= dice <= 6
# => true
max = 42
min = -13
range = Math.random() * (max - min) + min
-13 <= range < 42
# => true
For JavaScript, it's more straightforward and faster.
It is important to note that JavaScript's Math.random() cannot generate random number seeds from the generator to get a specific value. Details can be referred to to to Produce predictable random numbers.
Produces a number from 0 to n (excluded), multiplied by n.
Produces a number from 1 to n (included), multiplied by n and then added 1.