Understanding the algorithm of Visual C++'s rand() function

后端 未结 5 1570
渐次进展
渐次进展 2021-01-02 04:52

In C/C++, rand() and srand() are usually used by us when we want to get a random integer. But when I tried to rewrite it myself, I found it difficu

5条回答
  •  臣服心动
    2021-01-02 05:15

    It's just modular arithmetic. You're multiplying and adding to a number which is taken modulo 2^32 (for example), and returning the upper 16 bit as your "random" number. Because you're multiplying and adding numbers which are coprime to the modulus, this creates sort of uniformly distributed numbers.

    The careful choice of the two numbers is very important. For example, if you had used "* 4" and "+ 8", you would probably not experience a lot of randomness.

    This scheme is called linear congruential.

提交回复
热议问题