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 <cmath> #include <random> 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<double> 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:
The above is the detailed content of How to Generate Normally Distributed Random Numbers in C/C Without Boost?. For more information, please follow other related articles on the PHP Chinese website!