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

js獲取隨機數(shù)的問題

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

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

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

回答
編輯回答
陪妳哭

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

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

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

如果是取(0,10]的整數(shù),標準的方法就是Math.ceil(Math.random()*10),這時用floor怎么都會有問題的。

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

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

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

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

2018年2月28日 15:40