随机数,Math.floor(...)vs Math.ceil(...) [英] Random Number, Math.floor(...) vs Math.ceil(...)

查看:158
本文介绍了随机数,Math.floor(...)vs Math.ceil(...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多代码,其中会生成随机数,例如

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.

实际上,后面的代码

// 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]);
}

打印出

1: 250103
2: 250161
3: 250163
4: 249573

我想念什么?

快速OT:是否有更简洁的方法来声明和初始化频率?我的意思是像C ++中的frequencies[5] = { 0 }; ...

Quick OT: Is there a more succint way to declare and initialize frequencies? I mean like frequencies[5] = { 0 }; from C++...

推荐答案

,如

返回一个浮点伪随机数,范围为[0,1),即从0(包括)到不包括1(排除),然后您可以缩放到所需的范围./p>

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.

由于Math.random可以返回0,因此Math.ceil(Math.random()*10)也可以返回0,并且该值超出了[1..10]范围.

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.

关于第二个问题,请参见最有效的方法创建一个零填充的JavaScript数组?

About your second question, see Most efficient way to create a zero filled JavaScript array?

这篇关于随机数,Math.floor(...)vs Math.ceil(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆