Home > Backend Development > C++ > How Can We Generate Truly Uniformly Distributed Random Integers in a Specified Range?

How Can We Generate Truly Uniformly Distributed Random Integers in a Specified Range?

Barbara Streisand
Release: 2024-12-20 15:43:17
Original
186 people have browsed it

How Can We Generate Truly Uniformly Distributed Random Integers in a Specified Range?

Generating Uniformly Distributed Random Integers

In many programming applications, generating random integers within a specified range is a common requirement. However, ensuring that these integers are uniformly distributed presents a challenge. This article explores various approaches to achieving uniform distribution.

Existing Code and Limitations

The code provided by the user leverages the rand() function to generate random numbers within a given range. However, this approach suffers from a lack of uniformity, particularly for small ranges like <0, 1>. This is attributed to the low probability of rand() returning RAND_MAX, the maximum value.

Proposed Formula

To address this issue, the user devised a new formula:

( (max - min) * rand() + (RAND_MAX / (2 * (max - min))) ) / RAND_MAX
Copy after login

While this formula aims to improve uniformity, it still falls short, as evidenced by sampling data.

C Standard Library Solution

The C standard library provides an elegant and reliable solution to this problem. The std::random header includes a set of random number generators and distributions that can generate random numbers with uniform distribution.

#include <random>

// Initialize random-number engine with a seed
std::random_device rd;
std::mt19937 rng(rd());

// Define uniform integer distribution
std::uniform_int_distribution<int> uni(min, max);

// Generate random integer within range
auto random_integer = uni(rng);
Copy after login

This approach leverages well-tested and optimized code, ensuring uniform distribution and efficiency. It eliminates the need for reinventing the wheel and concerns about bias or seed values.

The above is the detailed content of How Can We Generate Truly Uniformly Distributed Random Integers in a Specified Range?. 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