generating a random number within range 0 to n where n can be > RAND_MAX

前端 未结 9 2073
梦毁少年i
梦毁少年i 2021-01-18 08:32

How can I generate a random number within range 0 to n where n can be > RAND_MAX in c,c++?

Thanks.

9条回答
  •  星月不相逢
    2021-01-18 08:46

    Consider a random variable which can take on values {0, 1} with P(0) = P(1) = 0.5. If you want to generate random values between 0 to 2 by summing two independent draws, you will have P(0) = 0.25, P(1) = 0.5 and P(2) = 0.25.

    Therefore, use an appropriate library unless you do not care at all about the PDF of the RNG.

    See also Chapter 7 in Numerical Recipes. (This is a link to the older edition but that's the one I studied anyway ;-)

提交回复
热议问题