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; }
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; }
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!