Rand() % 14 Generator Returns Limited Values
In a recent program, a developer encountered a problem where the rand() % 14 expression consistently produced values of only 6 or 13. Despite attempting to execute the code multiple times, the results remained consistent. The problem lies in the nature of the random number generator used by Apple's MCG.
As explained by Wikipedia, the MCG's multiplier of 16807 is divisible by 7. This means that the first random number generated after srand() will have only one bit of entropy when taken modulo 14, resulting in the limited range of values. This deficiency is attributed to the low-quality random number generator used by Apple.
A simple solution to this issue is to invoke rand() several times after srand() and discard the initial results. This will enhance the entropy of the generated numbers and resolve the issue of limited value output.
The above is the detailed content of Why Does `rand() % 14` Return Limited Values on Apple\'s MCG?. For more information, please follow other related articles on the PHP Chinese website!