在 JavaScript 中生成两个数字之间的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4959975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate random number between two numbers in JavaScript
提问by Mirgorod
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?
有没有办法在 JavaScript 中生成指定范围内的随机数(例如从 1 到 6:1、2、3、4、5 或 6)?
回答by Francisc
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
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.
它的“额外”功能是允许不以 1 开头的随机间隔。因此,例如,您可以获得 10 到 15 之间的随机数。灵活性。
回答by khr055
Important
重要的
The following code works only if the minimum value is 1
. It does not work for minimum values other than 1
.
以下代码仅在最小值为 时才有效1
。它不适用于除 之外的最小值1
。
If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
如果你想得到一个介于 1(并且只有 1)和 6之间的随机整数,你可以计算:
Math.floor(Math.random() * 6) + 1
Where:
在哪里:
- 1 is the start number
- 6 is the number of possible results (1 + start (6)- end (1))
- 1 是起始编号
- 6 是可能的结果数 (1 + start (6)- end (1))
回答by Lior Elrom
Math.random()
Math.random()
Returns an integer random numberbetween min (included) and max (included):
返回一个介于 min(包括)和 max(包括)之间的整数随机数:
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Or any random numberbetween min (included) and max (not included):
或min(包括)和 max(不包括)之间的任何随机数:
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful examples (integers):
有用的例子(整数):
// 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;
** And always nice to be reminded (Mozilla):
** 总是很高兴被提醒(Mozilla):
Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.
Math.random() 不提供加密安全的随机数。不要将它们用于与安全相关的任何事情。改用 Web Crypto API,更准确地说是 window.crypto.getRandomValues() 方法。
回答by Vishal
Other solutions:
其他解决方案:
(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1
(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1
回答by Faiz Mohamed Haneef
TL;DR
TL; 博士
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max + 1 - min))
}
To get the random number
generateRandomInteger(-20, 20);
获取随机数
generateRandomInteger(-20, 20);
EXPLANATION BELOW
解释如下
We need to get a random integer, say Xbetween min and max.
我们需要得到一个随机整数,比如最小值和最大值之间的X。
Right?
对?
i.e min <= X <= max
即 最小值 <= X <= 最大值
If we subtract min from the equation, this is equivalent to
如果我们从等式中减去 min,这等价于
0 <= (X - min) <= (max - min)
0 <= (X - min) <= (max - min)
Now, lets multiply this with a random number rwhich is
现在,让我们把它乘以一个随机数r,它是
0 <= (X - min) * r <= (max - min) * r
0 <= (X - min) * r <= (max - min) * r
Now, lets add back minto the equation
现在,让我们将min添加回方程
min <= min + (X - min) * r <= min + (max - min) * r
min <= min + (X - min) * r <= min + (max - min) * r
Now, lets chose a function which results in rsuch that it satisfies our equation range as [min,max]. This is only possible if 0<= r <=1
现在,让我们选择一个导致r的函数,使其满足我们的方程范围 [min,max]。这仅在0<= r <=1 时才有可能
OK. Now, the range of ri.e [0,1] is very similar to Math.random() function result. Isn't it?
好的。现在,r的范围即 [0,1] 与 Math.random() 函数结果非常相似。不是吗?
The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)
Math.random() 函数返回 [0, 1) 范围内的浮点伪随机数;即,从 0(含)到但不包括 1(不含)
For example,
例如,
Case r = 0
案例 r = 0
min
+ 0 * (max
-min
) = min
min
+ 0 * ( max
- min
) =分钟
Case r = 1
案例 r = 1
min
+ 1 * (max
-min
) = max
min
+ 1 * ( max
- min
) =最大值
Random Case using Math.random 0 <= r < 1
使用 Math.random 0 <= r < 1 的随机案例
min
+ r * (max
-min
) = X, where Xhas range of min<= X< max
min
+ r * ( max
- min
) = X,其中X 的范围为min<= X< max
The above result Xis 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.
上面的结果X是一个随机数字。然而由于 Math.random() 我们的左边界是包含的,而右边界是不包括的。为了包括我们的右边界,我们将右边界增加 1 并对结果进行取底。
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max + 1 - min))
}
To get the random number
获取随机数
generateRandomInteger(-20, 20)
;
generateRandomInteger(-20, 20)
;
回答by vladiim
回答by ryebr3ad
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
回答by Razan Paul
jsfiddle: https://jsfiddle.net/cyGwf/477/
jsfiddle:https://jsfiddle.net/cyGwf/477/
Random Integer: to get a random integer between min
and max
, use the following code
随机整数:要在min
和之间获取随机整数max
,请使用以下代码
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Random Floating Point Number: to get a random floating point number between min
and max
, use the following code
随机浮点数:要在min
和之间获取随机浮点数max
,请使用以下代码
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
回答by Petter Thowsen
Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
数学不是我的强项,但我一直在做一个项目,我需要在正负之间生成大量随机数。
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
E.g
例如
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.
当然,您也可以添加一些验证以确保您不会使用数字以外的任何其他内容执行此操作。还要确保 min 始终小于或等于 max。
回答by ElChupacabra
I wrote more flexible function which can give you random number but not only integer.
我写了更灵活的函数,它可以给你随机数,但不仅仅是整数。
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
Fixed version.
固定版。