MATLAB: Random numbers on the half open interval

random number generator

The function rand generates random numbers on the open interval (0,1). How can I generate random numbers on (0,1]?

Best Answer

The chance to get 1.0 exactly is 1:2^52. It is small, but when you want to be sure, that your code run properly, such details should not be neglected. I have personally seen a function crashing, because it did not catch the case, when the random value is exactly zero.
Although the algorithm for random numbers in [0, 1) is fast due to its simplicity, Matlab's RAND produces (0,1). I did not find an algorithm for this, so I assume, that the 0.0 is simply rejected. It is not trivial to inject it afterwards, but you can emulate the algorithm relative efficiently by obtaining two 32bit integers:
s = RandStream('mt19937ar','Seed',0)
RandStream.setGlobalStream(s);
r1 = randi([0, 4294967295]);
r2 = randi([0, 4294967295]);
r = (2097152 * r1 + fix(r2 / 2048)) / 9007199254740992;
For 0<=r<=1 you need:
r = (2097152 * r1 + fix(r2 / 2048)) / 9007199254740991;
For 0<r<=1:
r = (1 + 2097152 * r1 + fix(r2 / 2048)) / 9007199254740992;
Perhaps this is faster when UINT32 types are used in RANDI, but I cannot test this currently.
Well, I do not think that this is nice. Encapsulating this inside a C-MEX function would faster and perhaps more reliable. I'm working on such a function, because I'm really too confused by the changes in RAND, RNG and RANDSTREAM, when I write software which must be compatible with Matlab 6.5 to 2013a.
NOTE: There have been many bugs in published software for RNGs. Be sure to test this by your own before using it. Set r1 and r2 to 0 and 2^32-1 manually to check if the results really matches the claimed range!
Related Question