我在使用JavaScript生成正态分布的随机数(mu = 0 sigma = 1) 时遇到问题。随机分配正态分布的数字(javascript)
我试过Box-Muller的方法和ziggurat,但生成的一系列数字的平均值是0.0015或-0.0018 - 非常远离零!超过500,000个随机生成的数字,这是一个大问题。它应该接近零,类似于0.000000000001。
我无法弄清楚它是一个方法问题,还是JavaScript内置的Math.random()
生成的分布不完全一致的数字。
有人发现有类似的问题吗?
在这里你可以找到塔庙功能:
及以下的箱穆勒代码:
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];
}
这将是更容易帮助你,如果你发布你的代码。 – 2013-03-07 18:51:23