Generating a random double between a range of values

后端 未结 5 1345
天涯浪人
天涯浪人 2021-01-13 18:33

Im currently having trouble generating random numbers between -32.768 and 32.768. It keeps giving me the same values but with a small change in the decimal field. ex : 27.xx

5条回答
  •  旧时难觅i
    2021-01-13 18:50

    I should mention if you're using a C++11 compiler, you can use something like this, which is actually easier to read and harder to mess up:

    #include 
    #include 
    #include 
    
    
    int main()
    {
        //Type of random number distribution
        std::uniform_real_distribution dist(-32.768, 32.768);  //(min, max)
    
        //Mersenne Twister: Good quality random number generator
        std::mt19937 rng; 
        //Initialize with non-deterministic seeds
        rng.seed(std::random_device{}()); 
    
        // generate 10 random numbers.
        for (int i=0; i<10; i++)
        {
          std::cout << dist(rng) << std::endl;
        }
        return 0;
    }
    

    As bames53 pointed out, the above code can be made even shorter if you make full use of c++11:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::mt19937 rng; 
        std::uniform_real_distribution dist(-32.768, 32.768);  //(min, max)
        rng.seed(std::random_device{}()); //non-deterministic seed
        std::generate_n( 
             std::ostream_iterator(std::cout, "\n"),
             10, 
             [&]{ return dist(rng);} ); 
        return 0;
    }
    

提交回复
热议问题