example algorithm for generating random value in dataset with normal distribution?

…衆ロ難τιáo~ 提交于 2019-12-23 21:20:58

问题


I'm trying to generate some random numbers with simple non-uniform probability to mimic lifelike data for testing purposes. I'm looking for a function that accepts mu and sigma as parameters and returns x where the probably of x being within certain ranges follows a standard bell curve, or thereabouts. It needn't be super precise or even efficient. The resulting dataset needn't match the exact mu and sigma that I set. I'm just looking for a relatively simple non-uniform random number generator. Limiting the set of possible return values to ints would be fine. I've seen many suggestions out there, but none that seem to fit this simple case.


回答1:


Box-Muller transform in a nutshell:

First, get two independent, uniform random numbers from the interval (0, 1], call them U and V.

Then you can get two independent, unit-normal distributed random numbers from the formulae

X = sqrt(-2 * log(U)) * cos(2 * pi * V);
Y = sqrt(-2 * log(U)) * sin(2 * pi * V);

This gives you iid random numbers for mu = 0, sigma = 1; to set sigma = s, multiply your random numbers by s; to set mu = m, add m to your random numbers.




回答2:


My first thought is why can't you use an existing library? I'm sure that most languages already have a library for generating Normal random numbers.

If for some reason you can't use an existing library, then the method outlined by @ellisbben is fairly simple to program. An even simpler (approximate) algorithm is just to sum 12 uniform numbers:

X = -6 ## We set X to be -mean value of 12 uniforms
for i in 1 to 12:
   X += U

The value of X is approximately normal. The following figure shows 10^5 draws from this algorithm compared to the Normal distribution.



来源:https://stackoverflow.com/questions/3920310/example-algorithm-for-generating-random-value-in-dataset-with-normal-distributio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!