Random number generator, C++

后端 未结 8 2087
心在旅途
心在旅途 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:55

    As already said, you can use rand(). E.g.

    int n = rand() % 14620 + 1;

    does the job, but it is non-uniform. That means some values (low values) will occur slightly more frequently. This is because rand() yields values in the range of 0 to RAND_MAX and RAND_MAX is generally not divisible by 14620. E.g. if RAND_MAX == 15000, then the number 1 would be twice as likely as the number 1000 because rand() == 0 and rand() == 14620 both yield n==1 but only rand()==999 makes n==1000 true.

    However, if 14620 is much smaller than RAND_MAX, this effect is negligible. On my computer RAND_MAX is equal to 2147483647. If rand() yields uniform samples between 0 and RAND_MAX then, because 2147483647 % 14620 = 10327 and 2147483647 / 14620 = 146886, n would be between 1 and 10328 on average 146887 times while the numbers between 10329 and 14620 would occur on average 146886 times if you draw 2147483647 samples. Not much of a difference if you ask me.

    However, if RAND_MAX == 15000 it would make a difference as explained above. In this case some earlier posts suggested to use

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

    to make it 'more uniform'. Note that this only changes the numbers that occur more frequently since rand() still returns 'only' RAND_MAX distinct values. To make it really uniform, you would have to reject any integer form rand() if it is in the range between 14620*int(RAND_MAX/14620) and RAND_MAX and call rand() again. In the example with RAND_MAX == 15000 you would reject any values of rand() between 14620 and 15000 and draw again. For most application this is not necessary. I would worry more about the randomness of rand().

    0 讨论(0)
  • 2020-12-10 18:58

    the modulus operator is the most important, you can apply a limit with this modulus, check this out:

    // random numbers generation in C++ using builtin functions
    #include <iostream>
    
    using namespace std;
    
    #include <iomanip>
    
    using std::setw;
    
    #include <cstdlib>   // contains function prototype for rand
    
    int main()
    {
    // loop 20 times
    for ( int counter = 1; counter <= 20; counter++ ) {
    
        // pick random number from 1 to 6 and output it
        cout << setw( 10 ) << ( 1 + rand() % 6 );
    
        // if counter divisible by 5, begin new line of output
        if ( counter % 5 == 0 )
            cout << endl;
    
    }
    
    return 0;  // indicates successful termination
    
    } // end main
    
    0 讨论(0)
提交回复
热议问题