Generate random number between 0 and 1

21,112

Solution 1

Since C++11, use std::uniform_real_distribution

Solution 2

It really depends on how random you need the numbers to be. Generally, if I don't care about how random it is I will just use rand and divide by MAX_RAND (I bet matlab's rand is better than c's rand).

However, most of what I have done has required a better random number generator than the c function rand, and I don't need it to be cryptographically secure. In this case I use a mersenne twister class (http://www.bedaux.net/mtrand/) which has seemed to work better for the simulated annealing and monte carlo simulations that I sometimes find myself doing.

Also with this class, there is a way to get a random int32 and a radom double (between 0 and 1) out.

Solution 3

maybe you can use the RAND_MAX constant to divide the randomly generated integer

Share:
21,112

Related videos on Youtube

Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    Simple question but difficult to me. I want to generate uniformly distributed random numbers between 0 and 1, how can I do it? In matlab I am using rand, in C++ rand() returns integers.