Choosing the right random number distribution

How do I choose the appropriate random number distribution for my use case?

Choosing the right random number distribution depends on the characteristics of the random numbers you need. Here are a few common distributions and their use cases:

std::uniform_int_distribution

  • Generates random integers uniformly distributed within a specified range
  • Use when you need random integers with equal probability across the range
#include <iostream>
#include <random>

int main() {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<int> dist(1, 6);

  for (int i = 0; i < 5; ++i) {
    std::cout << dist(gen) << ' ';
  }
}
3 5 2 6 1

std::uniform_real_distribution

  • Generates random floating-point numbers uniformly distributed within a specified range
  • Use when you need random real numbers with equal probability across the range
#include <iostream>
#include <random>

int main() {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_real_distribution<double> dist(
    0.0, 1.0);  

  for (int i = 0; i < 5; ++i) {
    std::cout << dist(gen) << ' ';
  }
}
0.278498 0.534335 0.95655 0.157167 0.424719

std::normal_distribution

  • Generates random numbers according to a normal (Gaussian) distribution
  • Use when you need random numbers centered around a mean with a specified standard deviation
#include <iostream>
#include <random>

int main() {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::normal_distribution<double> dist(
    5.0, 2.0);  

  for (int i = 0; i < 5; ++i) {
    std::cout << dist(gen) << ' ';
  }
}
6.20473 3.94903 7.31954 1.69591 4.97183

Other distributions like std::exponential_distribution, std::poisson_distribution, and std::gamma_distribution are available for more specific use cases.

Consider the properties of your random number requirements, such as the range, probability distribution, and data type, to select the appropriate distribution.

Odds and Ends: 10 Useful Techniques

A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to use std::vector vs std::array
When should I use std::vector and when should I use std::array in C++?
Measuring execution time with
How can I measure the execution time of a function using the library?
Using [[nodiscard]] with custom types
How can I use the [[nodiscard]] attribute with my own custom types?
Creating a custom ClangFormat style
How can I create a custom ClangFormat style for my C++ project?
Integrating static analysis tools into your workflow
How can I integrate static analysis tools like Cppcheck into my C++ development workflow?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant