Rand() % 14 Only Generates Values 6 or 13: Breaking the Mystery
The issue you're facing arises due to the inherent limitations in the implementation of the rand() function on Apple platforms, as explained in the answer you provided. With the default parameters, the random number generator used by rand() produces a sequence that has limited entropy when divided by 14, causing it to cycle between only two values, 6 and 13.
To rectify this issue, you can take the following steps:
-
Call Rand() Multiple Times After Srand(): As suggested in the answer, discard the first few results generated by rand() after calling srand(time(NULL)). By doing so, you eliminate the initial cycle that produces only 6 and 13.
-
Use a Different Random Number Generator: If the above method does not resolve the issue, consider switching to a different random number generator that provides better entropy, such as the Mersenne Twister. You can find alternative random number generators in C libraries or as separate implementations.
-
Modify the Range of Random Numbers: As you mentioned in the edit, changing the range of rand() to 13 or 15 allows it to work correctly. This is because a multiplier of 15 (e.g., 752574) and 13 (e.g., 220379) are not divisible by their respective remainders. However, changing the range may not be suitable for your specific use case, especially if you need a random number between 0 and 13.
By addressing the underlying problem with the random number generator on Apple platforms, you can ensure that rand() % 14 produces a more evenly distributed sequence of values between 0 and 13.
The above is the detailed content of Why Does `rand() % 14` Only Generate 6 and 13 on Apple Platforms?. For more information, please follow other related articles on the PHP Chinese website!