<p>How can I convert a uniform distribution (as most random number generators produce, e.g. between 0.0 and 1.0) into a normal distribution? What if I want a mean and standard deviation of my choosing?</p>

[{'answer_id': 75720, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 6, 'selected': False, 'text': '<p>The <a href="http://en.wikipedia.org/wiki/Ziggurat_algorithm" rel="noreferrer">Ziggurat algorithm</a> is pretty efficient for this, although the <a href="http://en.wikipedia.org/wiki/Box-Muller_transform" rel="noreferrer">Box-Muller transform</a> is easier to implement from scratch (and not crazy slow).</p>\n'}, {'answer_id': 75889, 'author': 'hughdbrown', 'author_id': 10293, 'author_profile': 'https://Stackoverflow.com/users/10293', 'pm_score': 2, 'selected': False, 'text': '<p>I would use Box-Muller. Two things about this:</p>\n\n<ol>\n<li>You end up with two values per iteration<br>\nTypically, you cache one value and return the other. On the next call for a sample, you return the cached value.</li>\n<li>Box-Muller gives a Z-score<br>\nYou have to then scale the Z-score by the standard deviation and add the mean to get the full value in the normal distribution.</li>\n</ol>\n'}, {'answer_id': 75910, 'author': 'Brent.Longborough', 'author_id': 9634, 'author_profile': 'https://Stackoverflow.com/users/9634', 'pm_score': 1, 'selected': False, 'text': '<p>The standard Python library module <strong>random</strong> has what you want:</p>\n\n<blockquote>\n  <p>normalvariate(mu, sigma)<br>\n  Normal distribution. mu is the mean, and sigma is the standard deviation.</p>\n</blockquote>\n\n<p>For the algorithm itself, take a look at the function in random.py in the Python library.</p>\n\n<p>The <a href="http://docs.python.org/lib/module-random.html" rel="nofollow noreferrer">manual entry is here</a> </p>\n'}, {'answer_id': 77976, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<pre><code>function distRandom(){\n  do{\n    x=random(DISTRIBUTION_DOMAIN);\n  }while(random(DISTRIBUTION_RANGE)&gt;=distributionFunction(x));\n  return x;\n}\n</code></pre>\n'}, {'answer_id': 86885, 'author': 'Adi', 'author_id': 9090, 'author_profile': 'https://Stackoverflow.com/users/9090', 'pm_score': 5, 'selected': False, 'text': '<p>Changing the distribution of any function to another involves using the inverse of the function you want.</p>\n\n<p>In other words, if you aim for a specific probability function p(x) you get the distribution by integrating over it -> d(x) = integral(p(x)) and use its inverse: Inv(d(x)).  Now use the random probability function (which have uniform distribution) and cast the result value through the function Inv(d(x)).  You should get random values cast with distribution according to the function you chose.</p>\n\n<p>This is the generic math approach - by using it you can now choose any probability or distribution function you have as long as it have inverse or good inverse approximation.</p>\n\n<p>Hope this helped and thanks for the small remark about using the distribution and not the probability itself.</p>\n'}, {'answer_id': 88547, 'author': 'jilles de wit', 'author_id': 7531, 'author_profile': 'https://Stackoverflow.com/users/7531', 'pm_score': 3, 'selected': False, 'text': '<p>Use the central limit theorem <a href="http://en.wikipedia.org/wiki/Central_limit_theorem" rel="noreferrer">wikipedia entry</a> <a href="http://mathworld.wolfram.com/CentralLimitTheorem.html" rel="noreferrer">mathworld entry</a> to your advantage.</p>\n\n<p>Generate n of the uniformly distributed numbers, sum them, subtract n*0.5 and you have the output of an approximately normal distribution with mean equal to 0 and variance equal to <code>(1/12) * (1/sqrt(N))</code> (see <a href="http://en.wikipedia.org/wiki/Uniform_distribution_(continuous)" rel="noreferrer">wikipedia on uniform distributions</a> for that last one) </p>\n\n<p>n=10 gives you something half decent fast. If you want something more than half decent go for tylers solution (as noted in the <a href="http://en.wikipedia.org/wiki/Normal_distribution#Generating_values_for_normal_random_variables" rel="noreferrer">wikipedia entry on normal distributions</a>)</p>\n'}, {'answer_id': 196941, 'author': 'user5084', 'author_id': 5084, 'author_profile': 'https://Stackoverflow.com/users/5084', 'pm_score': 5, 'selected': False, 'text': '<p>Here is a javascript implementation using the polar form of the Box-Muller transformation.</p>\n\n<pre><code>/*\n * Returns member of set with a given mean and standard deviation\n * mean: mean\n * standard deviation: std_dev \n */\nfunction createMemberInNormalDistribution(mean,std_dev){\n    return mean + (gaussRandom()*std_dev);\n}\n\n/*\n * Returns random number in normal distribution centering on 0.\n * ~95% of numbers returned should fall between -2 and 2\n * ie within two standard deviations\n */\nfunction gaussRandom() {\n    var u = 2*Math.random()-1;\n    var v = 2*Math.random()-1;\n    var r = u*u + v*v;\n    /*if outside interval [0,1] start over*/\n    if(r == 0 || r &gt;= 1) return gaussRandom();\n\n    var c = Math.sqrt(-2*Math.log(r)/r);\n    return u*c;\n\n    /* todo: optimize this algorithm by caching (v*c) \n     * and returning next time gaussRandom() is called.\n     * left out for simplicity */\n}\n</code></pre>\n'}, {'answer_id': 3265174, 'author': 'Alexandre C.', 'author_id': 373025, 'author_profile': 'https://Stackoverflow.com/users/373025', 'pm_score': 6, 'selected': False, 'text': '<p>There are plenty of methods:</p>\n\n<ul>\n<li>Do <strong>not</strong> use Box Muller. Especially if you draw many gaussian numbers. Box Muller yields a result which is clamped between -6 and 6 (assuming double precision. Things worsen with floats.). And it is really less efficient than other available methods.</li>\n<li>Ziggurat is fine, but needs a table lookup (and some platform-specific tweaking due to cache size issues)</li>\n<li>Ratio-of-uniforms is my favorite, only a few addition/multiplications and a log 1/50th of the time (eg. <a href="http://books.google.fr/books?id=UQW_VL2H56IC&amp;pg=PA368&amp;lpg=PA368&amp;dq=%22ratio+of+uniforms%22+normal+distribution&amp;source=bl&amp;ots=PLY_fm-_az&amp;sig=sh7sfCZ7PeXSpyVcVi37BMhVYPo&amp;hl=fr&amp;ei=BlxATOmbK4HLOOjn9ZkN&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=8&amp;ved=0CD0Q6AEwBw#v=onepage&amp;q=%22ratio%20of%20uniforms%22%20normal%20distribution&amp;f=false" rel="noreferrer">look there</a>).</li>\n<li>Inverting the CDF <strong>is</strong> efficient (and overlooked, why ?), you have fast implementations of it available if you search google. It is mandatory for Quasi-Random numbers.</li>\n</ul>\n'}, {'answer_id': 7771542, 'author': 'Erik Aronesty', 'author_id': 627042, 'author_profile': 'https://Stackoverflow.com/users/627042', 'pm_score': 3, 'selected': False, 'text': '<p>Where R1, R2 are random uniform numbers:</p>\n<p>NORMAL DISTRIBUTION, with SD of 1:</p>\n<pre><code>sqrt(-2*log(R1))*cos(2*pi*R2)\n</code></pre>\n<p>This is exact... no need to do all those slow loops!</p>\n<p>Reference: <a href="http://dspguide.com/ch2/6.htm" rel="nofollow noreferrer">dspguide.com/ch2/6.htm</a></p>\n'}, {'answer_id': 8932273, 'author': 'Hippo', 'author_id': 1159325, 'author_profile': 'https://Stackoverflow.com/users/1159325', 'pm_score': 0, 'selected': False, 'text': '<p>I thing you should try this in EXCEL: <code>=norminv(rand();0;1)</code>. This will product the random numbers which should be normally distributed with the zero mean and unite variance. "0" can be supplied with any value, so that the numbers will be of desired mean, and by changing "1", you will get the variance equal to the square of your input.</p>\n\n<p>For example: <code>=norminv(rand();50;3)</code> will yield to the normally distributed numbers with MEAN = 50 VARIANCE = 9.</p>\n'}, {'answer_id': 34056202, 'author': 'Konstantin Burlachenko', 'author_id': 1154447, 'author_profile': 'https://Stackoverflow.com/users/1154447', 'pm_score': 0, 'selected': False, 'text': "<p>Q How can I convert a uniform distribution (as most random number generators produce, e.g. between 0.0 and 1.0) into a normal distribution?</p>\n\n<ol>\n<li><p>For software implementation I know couple random generator names which give you a pseudo uniform random sequence in [0,1] (Mersenne Twister, Linear Congruate Generator). Let's call it U(x)</p></li>\n<li><p>It is exist mathematical area which called probibility theory. \nFirst thing: If you want to model r.v. with integral distribution F then you can try just to evaluate F^-1(U(x)). In pr.theory it was proved that such r.v. will have integral distribution F.</p></li>\n<li><p>Step 2 can be appliable to generate r.v.~F without usage of any counting methods when F^-1 can be derived analytically without problems. (e.g. exp.distribution)</p></li>\n<li><p>To model normal distribution you can cacculate y1*cos(y2), where y1~is uniform in[0,2pi]. and y2 is the relei distribution.</p></li>\n</ol>\n\n<p>Q: What if I want a mean and standard deviation of my choosing?</p>\n\n<p>You can calculate sigma*N(0,1)+m.</p>\n\n<p>It can be shown that such shifting and scaling lead to N(m,sigma)</p>\n"}, {'answer_id': 36389129, 'author': 'Pepijn Schmitz', 'author_id': 1147600, 'author_profile': 'https://Stackoverflow.com/users/1147600', 'pm_score': 2, 'selected': False, 'text': '<p>It seems incredible that I could add something to this after eight years, but for the case of Java I would like to point readers to the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextGaussian--" rel="nofollow">Random.nextGaussian()</a> method, which generates a Gaussian distribution with mean 0.0 and standard deviation 1.0 for you.</p>\n\n<p>A simple addition and/or multiplication will change the mean and standard deviation to your needs.</p>\n'}, {'answer_id': 47537485, 'author': 'madx', 'author_id': 3138238, 'author_profile': 'https://Stackoverflow.com/users/3138238', 'pm_score': 1, 'selected': False, 'text': '<p>This is a Matlab implementation using the polar form of the <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform" rel="nofollow noreferrer">Box-Muller</a> transformation:</p>\n\n<p>Function <code>randn_box_muller.m</code>:</p>\n\n<pre><code>function [values] = randn_box_muller(n, mean, std_dev)\n    if nargin == 1\n       mean = 0;\n       std_dev = 1;\n    end\n\n    r = gaussRandomN(n);\n    values = r.*std_dev - mean;\nend\n\nfunction [values] = gaussRandomN(n)\n    [u, v, r] = gaussRandomNValid(n);\n\n    c = sqrt(-2*log(r)./r);\n    values = u.*c;\nend\n\nfunction [u, v, r] = gaussRandomNValid(n)\n    r = zeros(n, 1);\n    u = zeros(n, 1);\n    v = zeros(n, 1);\n\n    filter = r==0 | r&gt;=1;\n\n    % if outside interval [0,1] start over\n    while n ~= 0\n        u(filter) = 2*rand(n, 1)-1;\n        v(filter) = 2*rand(n, 1)-1;\n        r(filter) = u(filter).*u(filter) + v(filter).*v(filter);\n\n        filter = r==0 | r&gt;=1;\n        n = size(r(filter),1);\n    end\nend\n</code></pre>\n\n<p>And invoking <code>histfit(randn_box_muller(10000000),100);</code> this is the result:\n<a href="https://i.stack.imgur.com/s4LeV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s4LeV.png" alt="Box-Muller Matlab Histfit"></a></p>\n\n<p>Obviously it is really inefficient compared with the Matlab built-in <a href="https://it.mathworks.com/help/matlab/ref/randn.html" rel="nofollow noreferrer">randn</a>.</p>\n'}, {'answer_id': 53217176, 'author': 'great_minds_think_alike', 'author_id': 10625359, 'author_profile': 'https://Stackoverflow.com/users/10625359', 'pm_score': 0, 'selected': False, 'text': '<p>I have the following code which maybe could help:</p>\n\n<pre><code>set.seed(123)\nn &lt;- 1000\nu &lt;- runif(n) #creates U\nx &lt;- -log(u)\ny &lt;- runif(n, max=u*sqrt((2*exp(1))/pi)) #create Y\nz &lt;- ifelse (y &lt; dnorm(x)/2, -x, NA)\nz &lt;- ifelse ((y &gt; dnorm(x)/2) &amp; (y &lt; dnorm(x)), x, z)\nz &lt;- z[!is.na(z)]\n</code></pre>\n'}, {'answer_id': 54334875, 'author': 'peterweethetbeter', 'author_id': 10928083, 'author_profile': 'https://Stackoverflow.com/users/10928083', 'pm_score': 0, 'selected': False, 'text': '<p>It is also easier to use the implemented function rnorm() since it is faster than writing a random number generator for the normal distribution. See the following code as prove</p>\n\n<pre><code>n &lt;- length(z)\nt0 &lt;- Sys.time()\nz &lt;- rnorm(n)\nt1 &lt;- Sys.time()\nt1-t0\n</code></pre>\n'}, {'answer_id': 60476443, 'author': 'Alessandro Jacopson', 'author_id': 15485, 'author_profile': 'https://Stackoverflow.com/users/15485', 'pm_score': 1, 'selected': False, 'text': "<p>This is my JavaScript implementation of <strong>Algorithm P</strong> (<em>Polar method for normal deviates</em>) from Section 3.4.1 of Donald Knuth's book <em>The Art of Computer Programming</em>:</p>\n\n<pre><code>function normal_random(mean,stddev)\n{\n    var V1\n    var V2\n    var S\n    do{\n        var U1 = Math.random() // return uniform distributed in [0,1[\n        var U2 = Math.random()\n        V1 = 2*U1-1\n        V2 = 2*U2-1\n        S = V1*V1+V2*V2\n    }while(S &gt;= 1)\n    if(S===0) return 0\n    return mean+stddev*(V1*Math.sqrt(-2*Math.log(S)/S))\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/75677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8062/']