Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Box–Muller transform
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== C++ === The standard Box–Muller transform generates values from the standard normal distribution (''i.e.'' [[standard normal deviate]]s) with mean ''0'' and standard deviation ''1''. The implementation below in standard [[C++]] generates values from any normal distribution with mean <math>\mu</math> and variance <math>\sigma^2</math>. If <math>Z</math> is a standard normal deviate, then <math>X = Z\sigma + \mu</math> will have a normal distribution with mean <math>\mu</math> and standard deviation <math>\sigma</math>. The random number generator has been [[Random seed|seeded]] to ensure that new, pseudo-random values will be returned from sequential calls to the <code>generateGaussianNoise</code> function. <syntaxhighlight lang="cpp"> #include <cmath> #include <limits> #include <random> #include <utility> //"mu" is the mean of the distribution, and "sigma" is the standard deviation. std::pair<double, double> generateGaussianNoise(double mu, double sigma) { constexpr double two_pi = 2.0 * M_PI; //initialize the random uniform number generator (runif) in a range 0 to 1 static std::mt19937 rng(std::random_device{}()); // Standard mersenne_twister_engine seeded with rd() static std::uniform_real_distribution<> runif(0.0, 1.0); //create two random numbers, make sure u1 is greater than zero double u1, u2; do { u1 = runif(rng); } while (u1 == 0); u2 = runif(rng); //compute z0 and z1 auto mag = sigma * sqrt(-2.0 * log(u1)); auto z0 = mag * cos(two_pi * u2) + mu; auto z1 = mag * sin(two_pi * u2) + mu; return std::make_pair(z0, z1); } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)