Home >Backend Development >C++ >How to Generate Normally Distributed Random Numbers in C/C ?

How to Generate Normally Distributed Random Numbers in C/C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 16:51:12367browse

How to Generate Normally Distributed Random Numbers in C/C  ?

Generating Random Numbers Using Normal Distribution in C/C

The need to generate random numbers following a normal distribution often arises in various programming applications. In C/C , there are several techniques you can employ to achieve this.

One widely adopted approach is the Box-Muller transform. This method involves generating two independent uniform random numbers and transforming them using a mathematical formula to obtain normally distributed values. The Box-Muller transform is mathematically rigorous and produces accurate results.

Here's how to implement the Box-Muller transform in C/C :

#include <random>
#include <cmath>

// Generate a random number following a Gaussian distribution
double normal_rand() {
    static double z1;
    static bool ready = false;

    // If z1 is not ready, generate two uniform random numbers
    if (!ready) {
        double u1 = std::uniform_real_distribution<double>(0, 1)();
        double u2 = std::uniform_real_distribution<double>(0, 1)();
        z1 = std::sqrt(-2 * std::log(u1)) * std::cos(2 * M_PI * u2);
        ready = true;
    }

    // Return z1 and mark it as used
    ready = false;
    return z1;
}

In the above example, std::uniform_real_distribution generates uniform random numbers, while std::sqrt and std::cos perform the necessary mathematical transformations.

Utilizing the Box-Muller transform provides a straightforward and reliable way to generate random numbers following a normal distribution in C/C . By employing this technique, programmers can avoid the use of external libraries like Boost and leverage the standard C library's functionality.

The above is the detailed content of How to Generate Normally Distributed Random Numbers in C/C ?. 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