【发布时间】:2013-02-23 03:04:50
【问题描述】:
我在生成正态分布随机数时遇到问题 (mu=0 sigma=1) 使用 JavaScript。
我已经尝试过 Box-Muller 的方法和 ziggurat,但生成的一系列数字的平均值为 0.0015 或 -0.0018 - 与零相差甚远!超过 500,000 个随机生成的数字,这是一个大问题。它应该接近于零,例如 0.000000000001。
我不知道是方法问题,还是 JavaScript 的内置 Math.random() 生成的数字不完全均匀分布。
有没有人发现类似的问题?
您可以在这里找到 ziggurat 功能:
下面是 Box-Muller 的代码:
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];
}
【问题讨论】:
-
如果您发布代码会更容易帮助您。
标签: javascript random numbers generator