Question:
How do I easily generate random numbers following a normal distribution in C or C without using Boost libraries?
Answer:
Box-Muller Transform
The Box-Muller transform is a widely used method for generating normally distributed numbers from a uniform random number generator. It produces values that accurately adhere to a Gaussian distribution.
The mathematical formula for the Box-Muller transform is as follows:
x = sqrt(-2 * log(U1)) * cos(2 * π * U2) y = sqrt(-2 * log(U1)) * sin(2 * π * U2)
where:
Implementation:
To implement the Box-Muller transform in C/C , you can use the following code:
#include#include double box_muller() { std::random_device rd; // Seed the random number generator with a system clock seed std::default_random_engine rng(rd()); std::uniform_real_distribution dist(0.0, 1.0); double U1 = dist(rng); double U2 = dist(rng); double x = sqrt(-2 * log(U1)) * cos(2 * M_PI * U2); return x; }
Usage:
To generate a normally distributed random number, simply call the box_muller() function:
double random_number = box_muller();
The value of random_number will be a Gaussian-distributed random variable with mean 0 and standard deviation 1.
Note:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3