I cannot find a way to generate random number from uniform distribution in an open interval like (0,1).
(double)rand()/RAND_MAX;
will this include 0 and 1? If yes, what is the correct way to generate random number in an open interval?
I cannot find a way to generate random number from uniform distribution in an open interval like (0,1).
(double)rand()/RAND_MAX;
will this include 0 and 1? If yes, what is the correct way to generate random number in an open interval?
I haven't written C++ in ages but try the following code:
Given uniform distribution of a RNG with closed interval [a, b], the easiest method is to simply discard unwanted values an throw the dice again. This is both numerically stable and practically the fastest method to maintain uniformity.
(Disclaimer: RAND_MAX would have to be a power of two and < 2^52)
Take a look at std::uniform_real_distribution! You can use a more professional pseudo random number generator than the bulit-in of
<cstdlib>
called std::rand(). Here's a code example that print outs 10 random numbers in range [0,1):It is very unlikely to get exactly zero. If it is very important for you to not to get 0, you can check for it and generate another number.
And of course you can use random number engine specified, as
std::mt19937
(that is "very" random) or one of the fastest, thestd::knuth_b
.I haven't programmed in C++ for a number of years now, but when I did the implementation of rand was compiler specific. Implementations varied as to whether they covered [0,RAND_MAX], [0,RAND_MAX), (0,RAND_MAX], or (0,RAND_MAX). That may have changed, and I'm sure somebody will chime in if it has.
Assume that the implementation is over the closed interval [0,RAND_MAX], then
(double)(rand()+1)/(RAND_MAX+2);
should yield an open interval U(0,1) unlessRAND_MAX
is pushing up against the word size, in which case cast to long. Adjust the additive constants if your generator covers the range differently.An even better solution would be to ditch
rand
and use something like the Mersenne Twister from the Boost libraries. MT has different calls which explicitly give you control over the open/closed range of the results.