Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-11-23 00:55:16
Original
925 people have browsed it

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)
Copy after login

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 <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;
}
Copy after login

Usage:

To generate a normally distributed random number, simply call the box_muller() function:

double random_number = box_muller();
Copy after login

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.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template