2013-03-07 78 views
5

我在使用JavaScript生成正態分佈的隨機數(mu = 0 sigma = 1) 時遇到問題。隨機分配正態分佈的數字(javascript)

我試過Box-Muller的方法和ziggurat,但生成的一系列數字的平均值是0.0015或-0.0018 - 非常遠離零!超過500,000個隨機生成的數字,這是一個大問題。它應該接近零,類似於0.000000000001。

我無法弄清楚它是一個方法問題,還是JavaScript內置的Math.random()生成的分佈不完全一致的數字。

有人發現有類似的問題嗎?

在這裏你可以找到塔廟功能:

http://www.filosophy.org/post/35/normaldistributed_random_values_in_javascript_using_the_ziggurat_algorithm/

及以下的箱穆勒代碼:

function rnd_bmt() { 
    var x = 0, y = 0, rds, c; 

    // Get two random numbers from -1 to 1. 
    // If the radius is zero or greater than 1, throw them out and pick two 
    // new ones. Rejection sampling throws away about 20% of the pairs. 
    do { 
     x = Math.random()*2-1; 
     y = Math.random()*2-1; 
     rds = x*x + y*y; 
    } 
    while (rds === 0 || rds > 1) 

    // This magic is the Box-Muller Transform 
    c = Math.sqrt(-2*Math.log(rds)/rds); 

    // It always creates a pair of numbers. I'll return them in an array. 
    // This function is quite efficient so don't be afraid to throw one away 
    // if you don't need both. 
    return [x*c, y*c]; 
} 
+2

這將是更容易幫助你,如果你發佈你的代碼。 – 2013-03-07 18:51:23

回答

5

如果產生n獨立正態分佈隨機變量的standard deviation of the mean將是sigma/sqrt(n)

在你的情況下n = 500000sigma = 1所以平均值的標準誤差大約是1/707 = 0.0014。給定0平均值的95%置信區間將大約是其兩倍或(-0.0028, 0.0028)。你的樣本均值在這個範圍內。

您的期望獲得0.0000000000011e-12)不是數學上的基礎。要達到這個精度範圍,您需要生成約10^24樣本。在每秒10,000個樣本的情況下,仍然需要3個quadrillon年......這就是爲什麼如果可能的話,通過模擬來避免計算物體的好處。

在另一方面,你的算法似乎被正確執行:)

+0

非常感謝!沒有記住標準錯誤。 – user1658162 2013-03-07 19:31:20

+0

最後一個問題:如果我必須生成一個對數正態分佈的500000個數列,給定樣本的均值和方差,我是否必須調整一些參數才能得到與原始樣本完全相同的平均值? – user1658162 2013-03-07 19:36:35

+0

查看如何計算對數正態給定參數的均值和方差:http://en.wikipedia.org/wiki/Lognormal_distribution – 2013-03-07 22:20:53