1. 程式人生 > >js生成[n,m]的隨機數,js如何生成隨機數,javascript隨機數Math.random()

js生成[n,m]的隨機數,js如何生成隨機數,javascript隨機數Math.random()

一、預備知識 

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

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

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

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

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

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

Math.floor

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

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

因為結果在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);