在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML5  HTML/ js獲取隨機(jī)數(shù)的問(wèn)題

js獲取隨機(jī)數(shù)的問(wèn)題

比如說(shuō)獲取一個(gè)0~10的隨機(jī)數(shù),可以想到下面兩種

Math.ceil(Math.random()*10);
Math.floor(Math.random()*(10+1));

但是看到有人說(shuō)用Math.ceil(Math.random()*10);時(shí)取0的幾率極小。
用Math.floor(Math.random()*(10+1));時(shí),可均衡獲取0到10的隨機(jī)整數(shù)。
真的是這樣嗎?那是不是以后獲取隨機(jī)數(shù)用floor不用ceil呢?

回答
編輯回答
陪妳哭

ceil是向上取整,Math.ceil(Math.random()*10),當(dāng)只有取到0的時(shí)候才是0,所以幾率很小
floor是向下取整,Math.ceil(Math.random()*(10+1)),相當(dāng)于你在0到11間取,取到的數(shù)向下取整,可以相對(duì)來(lái)說(shuō)取到0-10的整數(shù)幾率差不多

2017年1月12日 23:25
編輯回答
不討囍

如果是取[0,10]的整數(shù),標(biāo)準(zhǔn)的方法就是Math.floor(Math.random()*(10+1))
如果是取[0,10)的整數(shù),標(biāo)準(zhǔn)的方法是Math.floor(Math.random()*10)
用ceil無(wú)論怎么處理都有問(wèn)題的。

如果是取(0,10]的整數(shù),標(biāo)準(zhǔn)的方法就是Math.ceil(Math.random()*10),這時(shí)用floor怎么都會(huì)有問(wèn)題的。

2018年3月31日 04:22
編輯回答
近義詞

樓上已經(jīng)將區(qū)別很好地解釋了 還有一種方法可以試試 ~~(0 + Math.random() * 10)

2018年3月28日 09:53
編輯回答
萌二代

這是一個(gè)數(shù)學(xué)問(wèn)題。首先你要明白Math.ceil是向上取整,也就是說(shuō),像0.000000000000000000001這樣這么小數(shù)向上取整完了也會(huì)是1;然后是取值范圍的問(wèn)題,$$Math.random() \in [0, 1)$$,向上取整后$$Math.ceil(Math.random()) \in [0, 1]$$,此時(shí),$$Math.ceil(Math.random()) = 0$$的充要條件即$$Math.random() = 0.0$$。假設(shè)Math.random()是理想的隨機(jī)數(shù)生成器(精確到小數(shù)點(diǎn)后無(wú)窮大位),則$$P(Math.random() = 0.0) = 0$$,若Math.random()精確到二進(jìn)制小數(shù)點(diǎn)后n位,則$$P(Math.random() = 0.0) = 1 / 2^n$$。你自己看看這概率有多小咯。

2018年2月28日 15:40