when generating normally-distributed random values, what is the most efficient way to define the range?

爷,独闯天下 提交于 2019-12-03 03:55:01

Subtracting two random numbers doesn't give you a normal distribution, it will give you numbers that decline linearly on both sides of zero. See the red diagram in this fiddle:

http://jsfiddle.net/Guffa/tvt5K/

To get a good approximation of normal distribution, add six random numbers together. See the green diagram in the fiddle.

So, to get normally distributed random numbers, use:

((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3

This method is based on the central limit theorem, outlined as the second method here: http://en.wikipedia.org/wiki/Normal_distribution#Generating_values_from_normal_distribution

I wanted to have gaussian random numbers between 0 and 1, and after many tests (thanks to @Guffa answer too) I found this to be the best:

function gaussianRand() {
  var rand = 0;

  for (var i = 0; i < 6; i += 1) {
    rand += Math.random();
  }

  return rand / 6;
}

And as a bonus:

function gaussianRandom(start, end) {
  return Math.floor(start + gaussianRand() * (end - start + 1));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!