javascript - 范围随机数 - 获取随机数
在JavaScript中生成两个数字之间的随机数 (12)
有什么方法可以在JavaScript中的指定范围内生成一个随机数(例如从1到6:1,2,3,4,5或6)?
Math.random()函数在[0,1)范围内返回一个浮点伪随机数; 即从0(包括)到1(不包括)
我们从0
到max-min
randomly
add
max-min
案例0
min
+ 0 *( max
- min
)= 分钟
情况1
min
+ 1 *( max
- min
)= 最大
使用Math.random 0 <= r <1的随机情况
min
+ r *( max
- min
)= X ,其中X具有min <= X < max的范围
上述结果X是一个随机数字。 但是,由于Math.random(),我们的左边界是包容性的,右边界是排他性的。 为了包含我们的右边界,我们增加1的右边界并将结果放置。
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max+1 - min))
}
获得随机数
generateRandomInteger(-20, 20)
;
Math.random()
从Math.random()开发者网络文档:
// Returns a random integer between min (included) and max (included)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
有用的例子:
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
例
返回1到10之间的随机数字:
Math.floor((Math.random() * 10) + 1);
结果可能是: 3
试试自己: here
-
或使用lodash / unexcore:
_.random(min, max)
其他解决方案
-
(Math.random() * 6 | 0) + 1
-
~~(Math.random() * 6) + 1
尽管有很多答案和几乎相同的结果。 我想补充我的回答并解释它的工作。 因为了解其工作非常重要,而不是复制粘贴一行代码。 生成随机数不过是简单的数学。
码:
function getR(lower, upper) {
var percent = (Math.random() * 100);
// this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
//now you have a percentage, use it find out the number between your INTERVAL :upper-lower
var num = ((percent * (upper - lower) / 100));
//num will now have a number that falls in your INTERVAL simple maths
num += lower;
//add lower to make it fall in your INTERVAL
//but num is still in decimal
//use Math.floor>downward to its nearest integer you won't get upper value ever
//use Math.ceil>upward to its nearest integer upper value is possible
//Math.round>to its nearest integer 2.4>2 2.5>3 both lower and upper value possible
console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
您可以使用crypto.getRandomValues()
来生成均匀分布的密码安全随机数,而不是使用Math.random()
。 这是一个例子:
function randInt(min, max) {
var MAX_UINT32 = 0xFFFFFFFF;
var range = max - min;
if (!(range <= MAX_UINT32)) {
throw new Error(
"Range of " + range + " covering " + min + " to " + max + " is > " +
MAX_UINT32 + ".");
} else if (min === max) {
return min;
} else if (!(max > min)) {
throw new Error("max (" + max + ") must be >= min (" + min + ").");
}
// We need to cut off values greater than this to avoid bias in distribution
// over the range.
var maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));
var rand;
do {
rand = crypto.getRandomValues(new Uint32Array(1))[0];
} while (rand > maxUnbiased);
var offset = rand % (range + 1);
return min + offset;
}
console.log(randInt(-8, 8)); // -2
console.log(randInt(0, 0)); // 0
console.log(randInt(0, 0xFFFFFFFF)); // 944450079
console.log(randInt(-1, 0xFFFFFFFF));
// Uncaught Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(24).fill().map(n => randInt(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9,
// 11, 8, 11, 8, 8, 8, 11, 9, 10, 12, 9, 11]
console.log(randInt(10, 8));
// Uncaught Error: max (8) must be >= min (10).
我写了更灵活的函数,它可以给你随机数,但不只是整数。
function rand(min,max,interval)
{
if (typeof(interval)==='undefined') interval = 1;
var r = Math.floor(Math.random()*(max-min+interval)/interval);
return r*interval+min;
}
var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
固定版本。
我发现Francisc的解决方案不包括结果中的最小或最大数字,所以我改变了它,如下所示:
function randomInt(min,max)
{
return Math.floor(Math.random()*(max-(min+1))+(min+1));
}
或者,在Underscore
_.random(min, max)
数学不是我的强项,但我一直在做一个项目,我需要在正面和负面之间产生大量的随机数。
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
例如
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
当然,您还可以添加一些验证,以确保您不会使用数字以外的任何方式进行此操作。 还要确保min始终小于或等于max。
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
它所做的“额外”是它允许不以1开头的随机时间间隔。例如,你可以得到一个从10到15的随机数。 灵活性。
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;