我在使用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