Home >Backend Development >C++ >How can I generate truly uniform random numbers within a specific range in C ?

How can I generate truly uniform random numbers within a specific range in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 15:58:10163browse

How can I generate truly uniform random numbers within a specific range in C  ?

Generate Random Numbers Uniformly Over an Entire Range

To generate random numbers within a specified interval [min, max] uniformly, the following guidelines should be considered:

Avoid Using rand() and Modulo Operator

Using rand() and the modulo operator, as demonstrated in the given code snippet, may not produce uniformly distributed random numbers. It depends on the range and the value of RAND_MAX.

C 11 Uniform Integer Distribution

With C 11, you can utilize std::uniform_int_distribution to generate random numbers within a range:

#include <iostream>
#include <random>

int main() {
    const int range_from = 0;
    const int range_to = 1000;
    std::random_device rand_dev;
    std::mt19937 generator(rand_dev());
    std::uniform_int_distribution<int> distr(range_from, range_to);

    std::cout << distr(generator) << '\n';
}

Other Random Number Generators

C 11 provides additional random number generators with various distributions, such as Bernoulli, Poisson, and normal.

Shuffling Containers

To shuffle a container randomly, use std::shuffle:

#include <iostream>
#include <random>
#include <vector>

int main() {
    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);
    std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';});
}

Boost.Random

If C 11 is not available, you can use Boost.Random, which offers an interface similar to C 11's random number generation facilities.

The above is the detailed content of How can I generate truly uniform random numbers within a specific range in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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