Odds and Ends: 10 Useful Techniques

# 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.

This Question is from the Lesson:

### Odds and Ends: 10 Useful Techniques

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

### Odds and Ends: 10 Useful Techniques

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

Part of the course:

## Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

### This course includes:

• 124 Lessons
• 550+ Code Samples
• 96% Positive Reviews
• Regularly Updated
• Help and FAQ
Free, Unlimited Access

### Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.