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

前端 未结 2 748
面向向阳花
面向向阳花 2021-02-06 17:37

FYI: random == pseudo-random

A. when generating uniformly-random numbers, I can specify a range, i.e.:

(Math.random()-Math.random())*10+5
//generates num         


        
相关标签:
2条回答
  • 2021-02-06 18:29

    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

    0 讨论(0)
  • 2021-02-06 18:40

    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));
    }
    
    0 讨论(0)
提交回复
热议问题