Search code examples
c++randomnumbers

What is the best way to generate random numbers in C++?


What is the best way to generate random numbers?


Solution

  • If and only if:

    • you are not looking for "perfect uniformity" or

    • you have no C++11 support and not even TR1 (thus you don't have another choice)

    then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:

    Here's the simple C-style function that generates random number from the interval from min to max, inclusive. Those numbers seem to be very close to being uniformly distributed.

    int irand(int min, int max) {
        return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
    }
    

    and don't forget to call srand before you use it:

    int occurrences[8] = {0};
    
    srand(time(0));
    for (int i = 0; i < 100000; ++i)
        ++occurrences[irand(1,7)];
    
    for (int i = 1; i <= 7; ++i)
        printf("%d ", occurrences[i]);
    

    output: 14253 14481 14210 14029 14289 14503 14235

    Also have a look at:
    Generate a random number within range?
    Generate random numbers uniformly over an entire range
    and find some time and watch at least first 11 minutes of aforementioned video

    Otherwise:

    use <random> just like it was pointed out by Kerrek SB already.