Home >Backend Development >C++ >How to Generate Normally Distributed Random Numbers in C/C using the Box-Muller Transform?

How to Generate Normally Distributed Random Numbers in C/C using the Box-Muller Transform?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 12:19:26347browse

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:

  1. Include the standard library header for accessing the rand() function.
  2. Define a function to generate a uniform random double following a range [0, 1). This can be done using:
double rand0to1() {
    return rand() / (RAND_MAX + 1.0);
}
  1. Implement the Box-Muller transform function:
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};
}
  1. Call the box_muller function to generate normally distributed random numbers as needed.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn