javascript 随机数,Math.floor(...) vs Math.ceil(...)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15830658/
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
Random Number, Math.floor(...) vs Math.ceil(...)
提问by doplumi
I've seen a lot of code where random numbers are generated like
我见过很多生成随机数的代码,例如
// random integers in the interval [1, 10]
Math.floor(Math.random()*10 + 1)
Anyway, I feel like I'm missing something. Why don't people use the more succint way
无论如何,我觉得我错过了一些东西。为什么人们不使用更简洁的方式
Math.ceil(Math.random()*10);
?
?
I tried to test the randomness and it seems true so far.
我试图测试随机性,到目前为止似乎是正确的。
In fact, the subsequent code
其实后面的代码
// will generate random integers from 1 to 4
var frequencies = [ 0, 0, 0, 0, 0 ]; // not using the first place
var randomNumber;
for ( var i = 0; i < 1*1000*1000; ++i ) {
randomNumber = Math.ceil(Math.random()*4);
frequencies[randomNumber]++;
}
for ( var i = 1; i <= 4; ++i ) {
console.log(i +": "+ frequencies[i]);
}
prints out
打印出来
1: 250103
2: 250161
3: 250163
4: 249573
What am I missing?
我错过了什么?
Quick OT: Is there a more succint way to declare and initialize frequencies? I mean like frequencies[5]?= { 0 };
from C++...
Quick OT:有没有更简洁的方法来声明和初始化频率?我的意思是像frequencies[5]?= { 0 };
来自 C++ ......
回答by Fabrizio Calderan
as stated in MDN referenceabout Math.random()
如在所述MDN参考关于Math.random()
Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
返回 [0, 1) 范围内的浮点伪随机数,即从 0(含)到但不包括 1(不含),然后您可以将其缩放到所需的范围。
Since Math.random can return 0
, then Math.ceil(Math.random()*10)
could also return 0
and that value is out of your [1..10]
range.
由于 Math.random 可以返回0
,那么Math.ceil(Math.random()*10)
也可以返回0
并且该值超出了您的[1..10]
范围。
About your second question, see Most efficient way to create a zero filled JavaScript array?
关于您的第二个问题,请参阅创建零填充 JavaScript 数组的最有效方法?
回答by Ja?ck
Math.floor()
is preferred here because of the range of Math.random()
.
Math.floor()
由于 的范围,这里是首选Math.random()
。
For instance, Math.random() * 10
gives a range of [0, 10)
. Using Math.floor()
you will neverget to the value of 10
, whereas Math.ceil()
maygive 0
.
例如,Math.random() * 10
给出一个范围[0, 10)
。使用Math.floor()
你永远不会得到 的价值10
,而Math.ceil()
可能会给0
。
回答by d'alar'cop
random integers in the interval [1, 10]:
区间 [1, 10] 中的随机整数:
Math.floor(Math.random()*10 + 1)
random integers in the interval [0, 10]:
区间 [0, 10] 中的随机整数:
Math.ceil(Math.random()*10);
Just depends what you need.
只看你需要什么。