# Random number generation open/closed interval

64 views (last 30 days)

Show older comments

##### 0 Comments

### Answers (3)

Jan
on 7 Aug 2011

Edited: Jan
on 21 Mar 2018

Most RNG create chunks of 32 random bits. They are converted to 0 <= x < 1 DOUBLEs by e.g.:

a = bitshift(randi([0, 2^32-1]), -5);

b = bitshift(randi([0, 2^32-1]), -6);

d = (a * 67108864.0 + b) / 9007199254740992.0

For 0 <= x <= 1:

d = (a * 67108864.0 + b) / 9007199254740991.0

For 0 < x <= 1:

d = (1 + a * 67108864.0 + b) / 9007199254740992.0

A simple rejection mechanism is correct: Creating 0 <= x <= 1 and rejecting 0 and/or 1 conserves the normal distribution.

Another frequently used method:

a = randi([0, 2^32-1]);

b = bitshift(randi([0, 2^32-1]), -11);

d = (2097152.0 * a + b) / 9007199254740992.0;

This is slower if implemented in C with unsigned integers, because UINT32->DOUBLE is implemented in software, while INT32->DOUBLE is a processor command.

##### 5 Comments

Oleg Komarov
on 6 Aug 2011

rand generates on the closed interval [...]

What comes to my mind:

- to generate on (...)

rand(...)*(1-2*eps) + eps

- to generate on (...]

rand(...)*(1-eps) + eps

- to generate on [...)

rand(...)*(1-eps)

EDIT

It seems the example is wronlgy indicating the closed interval and some tests confirm the that is actually (0,1):

nnz(rand(1e8,1) == 0)

nnz(rand(1e8,1) == 1)

No matches.

##### 6 Comments

Walter Roberson
on 8 Aug 2011

In some previous releases it was documented that the range for some generators was [2^(-53), 1-2^(-53)] rather than documenting it as (0,1) . This was in the 2008a documentation for example.

Peter, you yourself indicated earlier that the default twister algorithm is NOT (0,1) .

http://www.mathworks.com/matlabcentral/answers/879-does-matlab-have-a-birthday-problem#answer_1262

in which you wrote,

Walter, the User Guide includes this: "mt19937ar: The Mersenne Twister, as described in [9], with Mersenne prime 2^19937-1. This is the generator documented at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html. It has a period of 2^19937-1. Each U(0,1) value is created using two 32-bit integers from the generator; the possible values are all multiples of 2^-53 strictly within the interval (0,1)."

Notice in particular that this cannot generate anything on the interval [0, 2^(-53))

When I looked through the documentation of the specific ranges for each generator (this from before Mathworks removed the information from the reference pages where it belongs IMHO), I was unable to find any uniform distribution generator that was in fact dense over (0,1) .

Charles
on 7 Aug 2011

##### 2 Comments

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!