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

前端 未结 2 750
面向向阳花
面向向阳花 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

提交回复
热议问题