4

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.

1

3 Answers 3

11

Since C++11, use std::uniform_real_distribution

Sign up to request clarification or add additional context in comments.

Comments

1

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

7 Comments

Remember to cast it to a double/float! rand() / (float)RAND_MAX
ah very fast catch :) saved my answer from being useless
It's common to need numbers that are in the range [0,1) rather than [0,1], in which case divide by (RAND_MAX+1.0).
@pio note that I said +1.0, not +1.
@pio The conversion to float is necessary anyway to get uniforms between 0 and 1, so that seems like a reasonable place to kick accomplish it in C++.
|
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.