Home >Backend Development >C++ >Why Does `rand() % 14` Produce Non-Uniform Results?

Why Does `rand() % 14` Produce Non-Uniform Results?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 05:46:09954browse

Why Does `rand() % 14` Produce Non-Uniform Results?

Rand() % 14 Generates Non-Uniform Values

In an attempt to generate random values within a specific range, some programmers may encounter unusual behavior when using the rand() function. One common issue reported is that rand() % 14 consistently returns values of 6 or 13.

To understand this phenomenon, it's crucial to delve into the underlying algorithm of rand(). The specific implementation used on Apple's machines is based on the Multiply-with-Carry (MWC) Generator. Unfortunately, a weakness of this generator is its divisibility by 7, specifically the multiplier value of 16807.

As a result, the low-order bits of the first few random numbers generated immediately after initializing srand() have limited entropy. In the case of rand() % 14, the low-order bit will always have an identical value, leading to only two possible outcomes: 6 or 13.

To mitigate this issue, a straightforward solution is to discard the first few random numbers generated after initialization. By invoking rand() a few additional times without using the results, the internal state of the algorithm becomes more chaotic, and the uniform distribution of values is restored.

The above is the detailed content of Why Does `rand() % 14` Produce Non-Uniform Results?. 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