given a Math.random()
function which returns a number between [0,1) and min
max
values to specify the range, how can we generate numbers for the following cases:
Case we want integer:
A: (min,max) ?
B: [min,max) return Math.floor(Math.random() * (max - min)) + min;
C: (min,max] ?
D: [min,max] return Math.floor(Math.random() * (max - min + 1)) + min;
Case we want float:
A: (min,max) ?
B: [min,max) return Math.random() * (max - min) + min;
C: (min,max] ?
D: [min,max] ?
Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).
Integers
Your formula for B. is correct, everything else is obtained by trivial +1
-1
corrections:
(min, max) = [min + 1, max)
, therefore from B. we obtain
min + 1 + Math.floor(Math.random() * (max - min - 1))
min + Math.floor(Math.random() * (max - min))
(min, max] = max - [0, max - min)
, one could also write max - Math.floor(Math.random() * (max - min))
[min, max] = [min, max + 1)
, therefore: min + Math.floor(Math.random() * (max + 1 - min))
Floats. As V13 already pointed out, the question is somewhat ill-posed: if we consider single points as measure-zero sets, there is almost (in measure-theoretical sense) no difference between the four sets... However, if you want to guarantee that the excluded interval boundaries are never (not merely "almost never") sampled, and if you assume that there are no rounding errors, you could do something like this:
A: var middle = (min + max) / 2; var sign = Math.random() > 0.5 ? 1 : -1; return middle + sign * (max - min) / 2 * Math.random();
This solution puts a tiny little bit more mass on 0
, but this should be negligible for all practical purposes.
B: min + Math.random() * (max - min)
, yes.
max - Math.random() * (max - min)
, symmetric to the above.min + Math.random() * (max - min)
.The difference between A and D is the following: if we tried to use the formula min + Math.random() * (max - min)
in A, we might occasionally get a 0
(because the range of possible numbers is actually finite). However, no reasonable statistic could ever complain that the upper bound is not hit in D.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With