Home >Backend Development >C++ >How Can I Generate Truly Uniform Random Numbers in C ?

How Can I Generate Truly Uniform Random Numbers in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 19:42:11629browse

How Can I Generate Truly Uniform Random Numbers in C  ?

Generating Random Numbers Uniformly over an Entire Range

You seek to generate random numbers uniformly distributed within a specified interval, [min, max]. However, your current method is producing numbers clustered around a single point.

Avoiding rand()

The rand() function is often unreliable for generating uniform distributions. It relies on a modulus operator that can introduce biases.

C 11 Uniform Distribution

In C 11, consider using std::uniform_int_distribution for a more reliable solution:

#include <iostream>
#include <random>

int main()
{    
    const int range_from  = min;
    const int range_to    = max;
    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 Generators

The C 11 library offers various other random generators with different distributions. For example, std::shuffle can randomly reorder a container's elements.

Boost.Random Alternative

If C 11 is not available, consider using Boost.Random, which provides similar functionality.

The above is the detailed content of How Can I Generate Truly Uniform Random Numbers 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