Home > Backend Development > C++ > 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 ?

Patricia Arquette
Release: 2024-12-24 11:06:18
Original
212 people have browsed it

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 <random>

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

int random_number = distr(generator);
Copy after login

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 <random>
#include <vector>

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

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

Boost.Random

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

The above is the detailed content of How Can I Generate Uniformly Distributed Random Numbers Within a Specific Range in C ?. 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