Home > Backend Development > C++ > body text

Why Does `rand() % 14` Only Return 6 or 13 on Apple Systems?

Susan Sarandon
Release: 2024-11-24 20:59:21
Original
806 people have browsed it

Why Does `rand() % 14` Only Return 6 or 13 on Apple Systems?

Mystery of rand() % 14 Yielding Only 6 or 13

A programmer has encountered a peculiar issue where rand() % 14 consistently returns only 6 or 13 in their C program. Despite running the program multiple times, these values are the exclusive results.

The code in question:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main(int argc, const char * argv[])
{
    srand(time(NULL));
    cout << rand() % 14;
    return 0;
}
Copy after login

The culprit: Apple's MCG random number generator

As per Wikipedia, the multiplier utilized by Apple's Marsaglia-Crépeau random number generator (RNG) is 16807. Unfortunately, this multiplier is divisible by 7. Consequently, the initial random number generated after srand() only possesses one bit of entropy modulo 14, restricting it to two possible values: 6 or 13.

A simple solution

To circumvent this issue, one can discard a few random numbers generated immediately after srand(). By doing this, the entropy of the subsequent random numbers is increased, allowing for a wider range of values.

Here's the modified code:

int main(int argc, const char * argv[])
{
    srand(time(NULL));
    
    // Discard the first few random numbers to eliminate the bias
    for (int i = 0; i < 10; ++i)
        rand();
    
    cout << rand() % 14;
    return 0;
}
Copy after login

By discarding the first 10 random numbers, you effectively eliminate the bias introduced by the MCG RNG's flawed multiplier.

The above is the detailed content of Why Does `rand() % 14` Only Return 6 or 13 on Apple Systems?. 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