js如何生成[n,m]的隨機數

js如何生成[n,m]的隨機數

1、總結

一句話總結:生成隨機數就是用的Math的random方法。

 

一、Math.random()獲得的數據的左右開閉狀況是怎樣的?

左閉又開html

因此Math.floor(Math.random()*10);  //可均衡獲取0到9的隨機整數dom

 

二、如何隨機生成[1,max]的隨機數

Math.floor(Math.random()*max)+1;

 

 

2、js生成[n,m]的隨機數

1、預備知識 

Math.ceil();  //向上取整。函數

Math.floor();  //向下取整。學習

Math.round();  //四捨五入。spa

Math.random();  //0.0 ~ 1.0 之間的一個僞隨機數。【包含0不包含1】 //好比0.8647578968666494code

Math.ceil(Math.random()*10);      // 獲取從1到10的隨機整數 ,取0的機率極小。htm

Math.round(Math.random());   //可均衡獲取0到1的隨機整數blog

Math.floor(Math.random()*10);  //可均衡獲取0到9的隨機整數get

Math.round(Math.random()*10);  //基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10的概率少一半it

由於結果在0~0.4 爲0,0.5到1.4爲1...8.5到9.4爲9,9.5到9.9爲10。因此頭尾的分佈區間只有其餘數字的一半。

二 、生成[n,m]的隨機整數

函數功能:生成[n,m]的隨機整數。

在js生成驗證碼或者隨機選中一個選項時頗有用。。

//生成從minNum到maxNum的隨機數
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
} 

 過程分析:

Math.random()生成[0,1)的數,因此

Math.random()*5生成{0,5)的數。

一般指望獲得整數,因此要對獲得的結果處理一下。

parseInt(),Math.floor(),Math.ceil()和Math.round()均可獲得整數。

parseInt()和Math.floor()結果都是向下取整。

因此Math.random()*5生成的都是[0,4] 的隨機整數。

因此生成[1,max]的隨機數,公式以下:

// max - 指望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);

因此生成[0,max]到任意數的隨機數,公式以下:

// max - 指望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));

因此但願生成[min,max]的隨機數,公式以下:

// max - 指望的最大值
// min - 指望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);

本文做者starof,因知識自己在變化,做者也在不斷學習成長,文章內容也不定時更新,爲避免誤導讀者,方便追根溯源,請諸位轉載註明出處:http://www.cnblogs.com/starof/p/4988516.html有問題歡迎與我討論,共同進步。 

相關文章
相關標籤/搜索