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
Release: 2024-12-22 19:42:11
Original
696 people have browsed it

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';
}
Copy after login

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!

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