Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Instead of
Math.random()
, you can usecrypto.getRandomValues()
to generate evenly-distributed cryptographically-secure random numbers. Here's an example:Or, in Underscore
What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.
TL;DR
To get the random number
generateRandomInteger(-20, 20);
EXPLANATION BELOW
We need to get a random integer, say X between min and max.
Right?
i.e min <= X <= max
If we subtract min from the equation, this is equivalent to
0 <= (X - min) <= (max - min)
Now, lets multiply this with a random number r which is
0 <= (X - min) * r <= (max - min) * r
Now, lets add back min to the equation
min <= min + (X - min) * r <= min + (max - min) * r
Now, lets chose a function which results in r such that it satisfies our equation range as [min,max]. This is only possible if 0<= r <=1
OK. Now, the range of r i.e [0,1] is very similar to Math.random() function result. Isn't it?
For example,
Case r = 0
min
+ 0 * (max
-min
) = minCase r = 1
min
+ 1 * (max
-min
) = maxRandom Case using Math.random 0 <= r < 1
min
+ r * (max
-min
) = X, where X has range of min <= X < maxThe above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.
To get the random number
generateRandomInteger(-20, 20)
;Sense you need to add 1 to the max number, and then subtract the minimum number for any of this to work, and I need to make a lot of random Integers, this function works.
This works with both negative, and positive numbers, and I'm working on decimals for a library.