Issues with c++ 11 mersenne_twister_engine class

前端 未结 4 1100
谎友^
谎友^ 2021-01-25 11:43

I have been trying to use the c++ 11 mersenne_twister_engine class( http://www.cplusplus.com/reference/random/mersenne_twister_engine/) to generate numbers in the interval [0,1]

4条回答
  •  耶瑟儿~
    2021-01-25 12:09

    Using one of the distributions provided in the random header probably makes more sense. As Cubbi points out std::bernoulli_distribution looks like it fits your problem well. It will generate true or false according to the distribution parameter you pass in:

    #include 
    #include 
    #include 
    #include 
    
    const int WIDTH = 5 ;
    const int HEIGHT = 5 ;
    const double VERT_CONNECTIVITY = 0.25 ;
    
    int main()
    {
        std::random_device rd;
        std::mt19937 gen(rd());
    
        // give "true" 1/4 of the time
        // give "false" 3/4 of the time
        std::bernoulli_distribution d(VERT_CONNECTIVITY);
    
        std::vector vert_con( WIDTH * HEIGHT ) ;
    
        std::generate( std::begin(vert_con), std::end( vert_con ), [&] () { return d(gen) ; } ) ;
    
        for (int i=0; i < WIDTH * HEIGHT; i++) 
        {
            std::cout << vert_con[i] << " " ;
        }
        std::cout << std::endl ;
    
        return 0 ;
    }
    

提交回复
热议问题