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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3