如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
Use:
function getRandomizer(bottom, top) {
return function() {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
}
用法:
var rollDie = getRandomizer( 1, 6 );
var results = ""
for ( var i = 0; i<1000; i++ ) {
results += rollDie() + " "; // Make a string filled with 1000 random numbers in the range 1-6.
}
细分:
我们正在返回一个函数(从函数式编程中借用),当调用该函数时,将返回值bottom和top之间的随机整数,包括bottom。我们说“包含”是因为我们希望将底部和顶部都包含在可返回的数字范围内。这样,getRandomizer(1,6)将返回1、2、3、4、5或6。
(“底部”是较低的数字,“顶部”是较大的数字)
Math.random() * ( 1 + top - bottom )
Math.random()返回一个介于0和1之间的随机双精度,如果我们将其乘以1加上顶部和底部之间的差值,我们将得到一个介于介于0和1+b-a之间的双精度。
Math.floor( Math.random() * ( 1 + top - bottom ) )
Math.floor将数字向下舍入到最接近的整数。所以我们现在有了0和上下之间的所有整数。1看起来很令人困惑,但它需要存在,因为我们总是向下舍入,因此没有它就永远无法到达顶部数字。我们生成的随机小数需要在0到(1+上下)的范围内,这样我们就可以向下舍入,得到0到上下的整数:
Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom
上一个示例中的代码为我们提供了一个范围为0和上下的整数,因此我们现在需要做的就是将底部添加到该结果中,以获得范围为底部和顶部(含)的整数D
注意:如果你先传入一个非整数值或更大的数字,你会得到不希望的行为,但除非有人要求,否则我不会深入研究参数检查代码,因为它与原始问题的意图相去甚远。
其他回答
这是我对一个范围内的随机数的看法,就像我想得到一个基数到指数范围内的一个随机数。例如,基数=10,指数=2,理想情况下给出从0到100的随机数,依此类推。
如果它有助于使用它,这里是:
// Get random number within provided base + exponent
// By Goran Biljetina --> 2012
function isEmpty(value) {
return (typeof value === "undefined" || value === null);
}
var numSeq = new Array();
function add(num, seq) {
var toAdd = new Object();
toAdd.num = num;
toAdd.seq = seq;
numSeq[numSeq.length] = toAdd;
}
function fillNumSeq (num, seq) {
var n;
for(i=0; i<=seq; i++) {
n = Math.pow(num, i);
add(n, i);
}
}
function getRandNum(base, exp) {
if (isEmpty(base)) {
console.log("Specify value for base parameter");
}
if (isEmpty(exp)) {
console.log("Specify value for exponent parameter");
}
fillNumSeq(base, exp);
var emax;
var eseq;
var nseed;
var nspan;
emax = (numSeq.length);
eseq = Math.floor(Math.random()*emax) + 1;
nseed = numSeq[eseq].num;
nspan = Math.floor((Math.random())*(Math.random()*nseed)) + 1;
return Math.floor(Math.random()*nspan) + 1;
}
console.log(getRandNum(10, 20), numSeq);
//Testing:
//getRandNum(-10, 20);
//console.log(getRandNum(-10, 20), numSeq);
//console.log(numSeq);
Mozilla开发者网络页面上有一些示例:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
这是背后的逻辑。这是一个简单的三条规则:
Math.random()返回一个介于0(含)和1(不含)之间的数字。所以我们有一个这样的间隔:
[0 .................................... 1)
现在,我们需要一个介于min(含)和max(不含)之间的数字:
[0 .................................... 1)
[min .................................. max)
我们可以使用Math.random获取[min,max)区间的对应值。但是,首先我们应该通过从第二个区间减去min来稍微考虑一下问题:
[0 .................................... 1)
[min - min ............................ max - min)
这给出了:
[0 .................................... 1)
[0 .................................... max - min)
我们现在可以应用Math.random,然后计算对应的。让我们选择一个随机数:
Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)
因此,为了找到x,我们需要:
x = Math.random() * (max - min);
别忘了把min加回来,这样我们就可以得到[分钟,最大值]间隔内的数字:
x = Math.random() * (max - min) + min;
这是MDN的第一个函数。第二个,返回一个介于min和max之间的整数,两者都包含在内。
现在,对于整数,可以使用round、ceil或floor。
您可以使用Math.round(Math.random()*(max-min))+min,但这给出了一个非偶数分布。最小值和最大值都只有大约一半的掷骰机会:
min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max
如果将最大值排除在区间之外,那么它比最小值滚动的机会更小。
使用Math.floor(Math.random()*(max-min+1))+min,您可以获得完全均匀的分布。
min... min+1... ... max-1... max.... (max+1 is excluded from interval)
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max
你不能在这个等式中使用ceil()和-1,因为max现在的掷骰机会稍微少了一些,但你也可以掷(不需要的)min-1的结果。
使用此函数获取给定范围内的随机数:
function rnd(min, max) {
return Math.floor(Math.random()*(max - min + 1) + min);
}
random(min,max)生成介于min(含)和max(不含)之间的随机数Math.floor将数字向下舍入到最接近的整数函数generateRandomInteger(最小,最大){return数学下限(随机(最小值,最大值))}
因此,要生成一个介于4和8之间的随机整数,请使用以下参数调用上述函数:
generateRandomInteger(4, 9)
我在W3Schools上找到了这个简单的方法:
Math.floor((Math.random() * max) + min);
推荐文章
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误