Home >Backend Development >C++ >How to Generate Normally Distributed Random Numbers in C/C using the Box-Muller Transform?
Generating Normally Distributed Random Numbers in C/C
Generating random numbers that adhere to a normal distribution in C or C is a frequent task in various computational and statistical applications. This can be achieved effectively using the Box-Muller transform, a widely employed technique that leverages two uniform random numbers to produce a pair of normally distributed ones.
The Box-Muller transform relies on a simple mathematical formula:
x = sqrt(-2 * ln(u1)) * cos(2 * pi * u2) y = sqrt(-2 * ln(u1)) * sin(2 * pi * u2)
where u1 and u2 are two independent uniform random numbers generated in the range [0, 1]. These two equations define two independent random variables, x and y, which follow a normal distribution with zero mean and unit variance.
To implement this method in C/C , the following steps can be taken:
double rand0to1() { return rand() / (RAND_MAX + 1.0); }
pair<double, double> box_muller() { double u1 = rand0to1(); double u2 = rand0to1(); double x = sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2); double y = sqrt(-2.0 * log(u1)) * sin(2.0 * M_PI * u2); return {x, y}; }
This method effectively generates random numbers that follow a normal distribution without the need for external libraries.
The above is the detailed content of How to Generate Normally Distributed Random Numbers in C/C using the Box-Muller Transform?. For more information, please follow other related articles on the PHP Chinese website!