2013-03-07 154 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