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

后端 未结 5 1577
渐次进展
渐次进展 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:22

    As has been said it's a linear congruential, (you can look that up if you want in depth commentary on how these generate pseudo-random values)

    the seed is stored in _getptd()->_holdrand (hereafter called holdrand)

    This code "works" by doing the normal multiply and add step but then overflowing holdrand to get the implied "modulus" 0x100000000.

    I mention this because it's not immediately obvious, and generally not considered good style.

    Technically overflowing an integer variable isnvokes the undefined behaviour, but on most platforms it's quite predictable so Microsoft's engineers are ignoring that issue.

提交回复
热议问题