2017-03-28 40 views
1

我想知道創建概率的最佳或最可接受的方法是什麼。我做了一些研究,發現在的Math.random()主題一些有趣的問題和答案,如:Math.random的概率修飾符()

How random is JavaScript's Math.random?

Generating random whole numbers in JavaScript in a specific range?

我在尋找一個簡單的方式修改一個值將是真的概率使用Math.random()

例如,我知道Math.floor(Math.random() * 2)是用於產生1近50%時的有用方法:

-Math.random()生成隨機數0(含)之間和1(不包括)

- 如果產生的數是< 0.5,這個數字乘以2仍然會小於1,所以這個數字.floor()返回一個0如果生成的數字大於0.5,這個數字乘以2會大於1,所以這個數字.floor()返回0這個數字.floor()返回一個1

我想歪曲使用「修飾符」得到1的概率,這是clo因爲我必須得到理想的概率...

每次運行代碼片段時,控制檯都會打印命中率。正如你所看到的,它們幾乎是準確的,但並不完全。我通過反覆試驗提出了指數修改功能。有什麼辦法可以讓這個更準確嗎?

var youHit = Math.floor(Math.random() * 2); 
 
var totalTries = 0; 
 
var hits = 0; 
 

 
var pointNine = 0.9; // you want 90% of tries to hit 
 
var pointEight = 0.8;// you want 80% of tries to hit 
 
var pointSeven = 0.7;// you want 70% of tries to hit 
 
    
 
function probCheck(modifier) { 
 
    var exponent = 1 + (1 - modifier) + (1 - modifier)*10; 
 
    for (var x = 0; x < 100; x++) { 
 
    youHit = Math.floor((Math.pow(modifier, exponent)) + (Math.random() * 2)); 
 
    totalTries += 1; 
 
    if (youHit) { 
 
     hits += 1; 
 
    } 
 
    } 
 
    console.log("final probability check: " + hits/totalTries); 
 
}; 
 

 
probCheck(pointNine); 
 
probCheck(pointEight); 
 
probCheck(pointSeven);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

越「精確」,你就越沒有隨機性。 – JDB

+0

你並沒有重置全局變量'hits'和'totalTries',它們可能不應該是全局變量。 – James

回答

3

指數沒有真正意義在這裏。退一步:上的均勻分佈的數[0,1)小於在相同範圍內的概率爲X的x,所以:

function randomHit(modifier) { 
    return Math.random() < modifier; 
} 

測試:

function randomHit(modifier) { 
 
    return Math.random() < modifier; 
 
} 
 

 
function probCheck(modifier) { 
 
    var totalTries = 100; 
 
    var hits = 0; 
 

 
    for (var x = 0; x < totalTries; x++) { 
 
    if (randomHit(modifier)) { 
 
     hits++; 
 
    } 
 
    } 
 

 
    console.log("final probability check: " + hits/totalTries); 
 
} 
 

 
probCheck(0.9); 
 
probCheck(0.8); 
 
probCheck(0.7);

+0

我有一種感覺,它比我做它更簡單...你能再次解釋你的意思嗎?「在[0,1]上的均勻分佈數小於x在同一範圍內的概率X」? –

+1

@AdamM .:如果你有一個從0到1的隨機數,它小於0.6的概率是60%。或者0.8和80%,或者0.2和20%。 – Ryan