Creating a uniform random integer in C ++

The problem is that I need to create a random integer from 0 to 999 (to study the mathematical hypothesis). All values ​​should have the same probability of arrival.

I tried rand(), but with RAND_MAXequal to 32767 (on my compiler), this means that only acceptance rand() % 1000leads to the fact that the first 1-767 will be much more likely (and that provided that all possibilities have the same probability in rand()the first place) .

I use Windows, so /dev/randomit is not an option.

+5
source share
6 answers

You can do something like this using uniform_int_distributionwith C ++ 11:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 999);

    for (int n=0; n<1000; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}
+18

, , rand() . :

. rand() , ( 1 0 ). rand() , .

++ 11 , , , , .

( , ), std::mersenne_twister_engine

+9

, - [32000, 32767] % 1000 . .

/ ( ++ 11, ), PRNG, rand.

+3

, " ". , 1-767 ( , 0-767, ), . , "" , ++ 11 Mersenne Twister, .

: http://www.cplusplus.com/reference/random/mt19937/

+2

, rand() [0,RAND_MAX] RAND_MAX, , 32767.

u=(double)rand();
d=(double)RAND_MAX;
double div= u/d;
double res=div*interval_range;

, RAND_MAX interval_range. . , RAND_MAX, , , rand(), ( rand() , ). - , ( ). :

enter image description here

"", , ( , std_dev, ..), .

:

int main{ 
    int o=RAND_MAX;
    std::map<int,int> m1;
    int min=0,max=999;

    for (int i=0; i<1000*9994240; ++i){//9994240=305*32768  32768=RAND_MAX+1
        int r=rand();
        if(r<=max){
            m1[r]++;
        }
    }
    for (auto & i : m1)
        std::cout << i.first << " : " << i.second << '\n';
}

Result: 0: 42637 1: 42716 2: 42590 3: 42993 4: 42936 5: 42965 6: 42941 7: 42705 8: 42944 9: 42707 10: 42860 11: 43012 12: 42793 // ... 995: 42861 996 : 42911 997: 42865 998: 42877 999: 43159


you can achieve the desired result in any domain this way:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 1000);

    for (int n=0; n<1000; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

however, in this case, you really should use boost:

#include <iostream>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
using namespace std;

int main() {
      typedef boost::mt19937 RNGType;
      RNGType rng;
      boost::uniform_int<> zero_to_n( 0, 999 );
      boost::variate_generator< RNGType, boost::uniform_int<> >
                    dice(rng, zero_to_n);
          int n  = dice();

}
+1
source
  • Get a random number using rand().

  • Divide it by RAND_MAX. You will get a floating point number between 0 and 1.

  • Multiply this number by 1000.

0
source

All Articles