第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Math.floor() 優(yōu)于 Math.round()?

為什么 Math.floor() 優(yōu)于 Math.round()?

侃侃爾雅 2021-08-20 16:51:49
我在 FreeCodeCamp 中發(fā)現(xiàn),解決在范圍內獲取隨機整數(shù)的問題是使用Math.floor. 四舍五入是不準確的。它返回等于或小于。這不是我想的。這是給定的公式: Math.floor(Math.random() * (max - min + 1)) + min有誰知道為什么它更多地用于四舍五入到最接近的整數(shù)?
查看完整描述

3 回答

?
30秒到達戰(zhàn)場

TA貢獻1828條經(jīng)驗 獲得超6個贊

摘要:由于與Math.round()中值min和max均不足。


讓我們舉個例子,比較一下分別使用Math.floor()和時的結果Math.random()。


為了清楚起見,我添加了我們正在比較的兩個公式:


min = 0;

max = 3;


result = Math.round(Math.random() * (max - min)) + min;

result = Math.floor(Math.random() * (max - min + 1)) + min;


| result | Math.round() | Math.floor() |

|:------:|:------------:|:------------:|

|    0   |  0.0 - 0.499 |   0 - 0.999  |

|    1   |  0.5 - 1.499 |   1 - 1.999  |

|    2   |  1.5 - 2.499 |   2 - 2.999  |

|    3   |  2.5 - 2.999 |   3 - 3.999  |

您會看到這一點,0并且3產生它們的范圍只有Math.random()示例中所有其他范圍的一半。


查看完整回答
反對 回復 2021-08-20
?
慕村9548890

TA貢獻1884條經(jīng)驗 獲得超4個贊

Math.floor(Math.random() * (max - min + 1)) + min

會給你一個 [min, max] 范圍內的隨機數(shù),因為 Math.random() 給你 [0, 1)。讓我們用 Math.round 代替 Math.floor,Math.random() 給你 [0, 1),如果你乘以 10,你會得到 [0, 10)。這是一個浮點數(shù),如果你把它四舍五入,你會得到 [0, 10] 作為整數(shù)。但是,如果將其四舍五入,則會得到 [0, 10) 作為整數(shù)。

在大多數(shù)隨機函數(shù)中,規(guī)范是返回 [min, max)。

為了回答你的問題,作者使用了Math.floor,如果使用Math.round,隨機數(shù)將在[min, max]而不是[min, max+1]的范圍內。

來自維基百科

區(qū)間 主條目:區(qū)間(數(shù)學) 括號 ( ) 和方括號 [ ] 也可用于表示區(qū)間。符號 {\displaystyle [a,c)} [a, c) 用于表示從 a 到 c 的區(qū)間,該區(qū)間包含 {\displaystyle a} a 但不包括 {\displaystyle c} c。也就是說, {\displaystyle [5,12)} [5, 12) 將是 5 到 12 之間所有實數(shù)的集合,包括 5 但不包括 12。這些數(shù)字可能盡可能接近 12,包括 11.999等等(任何有限數(shù)量的 9),但不包括 12.0。在一些歐洲國家,符號 {\displaystyle [5,12[} [5,12[] 也用于此目的。


查看完整回答
反對 回復 2021-08-20
?
慕桂英546537

TA貢獻1848條經(jīng)驗 獲得超10個贊

Math.floor(Math.random())將始終返回0Math.round(Math.random())將返回,0 or 1因此Math.round()隨機數(shù)將遵循非均勻分布。這可能無法滿足您的需求。


查看完整回答
反對 回復 2021-08-20
  • 3 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號