Random float number generation

后端 未结 14 1314
孤城傲影
孤城傲影 2020-11-22 05:05

How do I generate random floats in C++?

I thought I could take the integer rand and divide it by something, would that be adequate enough?

14条回答
  •  清酒与你
    2020-11-22 05:35

    If you are using C++ and not C, then remember that in technical report 1 (TR1) and in the C++0x draft they have added facilities for a random number generator in the header file, I believe it is identical to the Boost.Random library and definitely more flexible and "modern" than the C library function, rand.

    This syntax offers the ability to choose a generator (like the mersenne twister mt19937) and then choose a distribution (normal, bernoulli, binomial etc.).

    Syntax is as follows (shameless borrowed from this site):

      #include 
      #include 
    
      ...
    
      std::tr1::mt19937 eng;  // a core engine class 
      std::tr1::normal_distribution dist;     
    
      for (int i = 0; i < 10; ++i)        
          std::cout << dist(eng) << std::endl;
    

提交回复
热议问题