Random number generator, C++

后端 未结 8 2105
心在旅途
心在旅途 2020-12-10 18:25

I know there is a bit of limitations for a random number generation in C++ (can be non-uniform). How can I generate a number from 1 to 14620?

Thank you.

8条回答
  •  渐次进展
    2020-12-10 18:43

    srand() / rand() are the functions you need, as others have answered.

    The problem with % is that the result is decidedly non-uniform. To illustrate, imagine that rand() returns a range of 0-3. Here are hypothetical results of calling it 4000 times:

    0 - 1000 times
    1 - 1000 times
    2 - 1000 times
    3 - 1000 times
    

    Now if you do the same sampling for (rand() % 3), you notice that the results would be like:

    0 - 2000 times
    1 - 1000 times
    2 - 1000 times
    

    Ouch! The more uniform solution is this:

    int n = (int)(((((double)std::rand()) / RAND_MAX) * 14620) + 1);

    Sorry for the sloppy code, but the idea is to scale it down properly to the range you want using floating point math, and convert to integer.

提交回复
热议问题