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

前端 未结 9 2075
梦毁少年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:50

    If you're looking for a uniform distribution (or any distribution for that manner) , you must take care that the statistical properties of the output are sufficient for your needs. If you can't use the output of a random number generator directly, you should be very careful trying to combine numbers to achieve your needs.

    At a bare minimum you should make sure the distribution is appropriate. If you're looking for a uniform distribution of integers from 0 to M, and you have some uniform random number generator g() to produce outputs that are smaller than M, make sure you do not do one of the following:

    • add k outputs of g() together until they're large enough (the result is nonuniform)
    • take r = g() + (g() << 16), then compute r % M (if the range of r is not an even multiple of M, it will weight certain values in the range slightly more than others; the shift-left itself is questionable unless g() outputs a range between 0 and a power of 2 minus 1)

    Beyond that, there is the potential for cross-correlation between terms of the sequence (random number generators are supposed to produce independent identically-distributed outputs).

    Read The Art of Computer Programming vol. 2 (Knuth) and/or Numerical Recipes and ask questions until you feel confident.

提交回复
热议问题