"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Generate Normally Distributed Random Numbers in C/C++ Without Boost?

How to Generate Normally Distributed Random Numbers in C/C++ Without Boost?

Published on 2024-11-23
Browse:630

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

Generating Random Numbers with a Normal Distribution in C/C

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:

  • U1 and U2 are uniformly distributed random numbers between 0 and 1
  • x and y are normally distributed random numbers with mean 0 and standard deviation 1

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:

  • The Box-Muller transform also produces a second result, y, but this can be discarded or saved for later use.
  • If you need to generate normally distributed numbers with a mean other than 0 or a standard deviation other than 1, you can multiply the result by a constant.
Latest tutorial More>

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