"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 Can I Generate Uniformly Distributed Random Numbers Within a Specific Range in C++?

How Can I Generate Uniformly Distributed Random Numbers Within a Specific Range in C++?

Published on 2024-12-21
Browse:256

How Can I Generate Uniformly Distributed Random Numbers Within a Specific Range in C  ?

Uniform Random Number Generation Across a Range

You seek a method to uniformly generate random numbers within a specified range [min, max].

Flaws with rand

Your current implementation using rand() and the modulus operator may not ensure uniform distribution, as its behavior depends on RAND_MAX and the range itself.

C 11 and Uniform Range Generation

In C 11, std::uniform_int_distribution offers a solution tailored to this need:

#include 

std::uniform_int_distribution distr(min, max);
std::random_device rand_dev;
std::mt19937 generator(rand_dev());

int random_number = distr(generator);

Additional Features of

The header provides a vast array of random number generators with varying distributions, such as Bernoulli, Poisson, and normal.

Container Shuffling

To shuffle a container, employ std::shuffle:

#include 
#include 

std::vector vec = {4, 8, 15, 16, 23, 42};
std::random_device random_dev;
std::mt19937 generator(random_dev());

std::shuffle(vec.begin(), vec.end(), generator);

Boost.Random

If using a C 11 compiler is not feasible, consider Boost.Random, which features a similar interface to the C 11 counterpart.

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