Make JavaScript Math.random() useful這篇文章是由Andrew Penry所寫,他將Javascript中的亂數函式Math.random()使用方式做了詳細說明。下列將原文的例子重新列表一次

/*
【原始】
 範例:Math.random()
值範圍:0 ~ 0.9999999(無窮小數)

【最大值】
 範例:Math.random() * 3
值範圍:0 ~ 2.9999999(無窮小數)

【有最小值】
 範例:Math.random() * 2 + 1
值範圍:1 ~ 1.9999999(無窮小數)

【四捨五入】
 範例:Math.round(Math.random*2+1)
值範圍:(1) - (1.5) - (2) - (2.5) - (3)

【取得大於指定數的最小整數值】
 範例:Math.ceil(Math.random()*2)
值範圍:(0) - (0.5) - (1) - (1.5) - (2)
 注意:在Javascript中,Math.ceil(0) 等於 0

【取得小於指定數的最大整數值】
 範例:Math.floor(Math.random()*2+1)
值範圍:(1) - (1.5) - (2) - (2.5) - (3)
*/

//下列為自訂範圍值的亂數函式(最小值,最大值)
function usefloor(min,max) {
  return Math.floor(Math.random()*(max-min+1)+min);
}
function useceil(min,max) {
  return Math.ceil(Math.random()*(max-min+1)+min-1);
}
function useround(min,max) {
  return Math.round(Math.random()*(max-min)+min);
}

根據Andrew Penry的測試結果,使用floor的方法,各數出現的機率比較平均,所以floor會較好的選擇

arrow
arrow
    全站熱搜

    低溫烘培 發表在 痞客邦 留言(1) 人氣()