Math.random()
函数返回浮点伪随机数,范围为[0,1),范围从0(包括0)到但不包括1(独家)
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)
因此,生成0到1之间的随机数,并从中减去0.5.
So, generate random numbers between 0 and 1 and subtract 0.5 from it.
Math.random() - 0.5
注意: Math.random()
不需要任何参数.因此,您不能指定任何范围.
Note: Math.random()
doesn't expect any parameters. So, you cannot specify any range.
如果要在一个范围之间生成随机数,请使用
If you want to generate random numbers between a range, use the example snippets in MDN,
// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
具有范围的演示
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function appendToResult(value) {
document.getElementById("result").innerHTML += value + "<br />";
}
document.getElementById("result").innerHTML = "";
for (var i = 0; i < 10; i += 1) {
appendToResult(getRandomArbitrary(-0.35, 0.35));
}
<pre id="result" />
之所以有效,是因为表达式
This works because, the expression
Math.random() * (max - min) + min
将以以下方式进行评估.首先,
will be evaluated in the following manner. First,
Math.random()
将被评估为获得0到1之间的随机数,然后
will be evaluated to get a random number in the range 0 and 1 and then
Math.random() * (max - min)
它将乘以 max
和 min
值之间的差.在您的情况下,假设 max
是 0.35
,而 min
是 -0.35
.因此, max-min
变为 0.7
.因此, Math.random()*(max-min)
给出一个在 0
和 0.7
范围内的数字(因为即使Math.random()
生成 1
,将其与 0.7
相乘,结果将变为 0.7
.).然后,你做
it will be multiplied with the difference between max
and min
value. In your case, lets say max
is 0.35
and min
is -0.35
. So, max - min
becomes 0.7
. So, Math.random() * (max - min)
gives a number in the range 0
and 0.7
(because even if Math.random()
produces 1
, when you multiply it with 0.7
, the result will become 0.7
). Then, you do
Math.random() * (max - min) + min
所以,就您的情况而言,基本上变成了
So, for your case, that basically becomes,
Math.random() * (0.35 - (-0.35)) + (-0.35)
(Math.random() * 0.7) - 0.35
因此,如果(Math.random()* 0.7)
生成任何大于 0.35
的值,因为您从中减去了 0.35
,它变成介于 0
和 0.35
之间的某个数字.如果(Math.random()* 0.7)
生成的值小于 0.35
,则由于您从中减去了 0.35
,因此它成为一个介于 -0.35
和 0
.
So, if (Math.random() * 0.7)
generates any value greater than 0.35
, since you subtract 0.35
from it, it becomes some number between 0
and 0.35
. If (Math.random() * 0.7)
generates a value lesser than 0.35
, since you subtract 0.35
from it, it becomes a number between -0.35
and 0
.
这篇关于如何随机生成-0.5到0.5范围内的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!