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

前端 未结 2 774
面向向阳花
面向向阳花 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: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));
    }
    

提交回复
热议问题