FreeMat: RAND Uniform Random Number Generator

FreeMat

- Main Page
- Related Pages

RAND Uniform Random Number Generator

Section: Random Number Generation

# Usage

Creates an array of pseudo-random numbers of the specified size. The numbers are uniformly distributed on `[0,1)`. Two seperate syntaxes are possible. The first syntax specifies the array dimensions as a sequence of scalar dimensions:

      y = rand(d1,d2,...,dn).

The resulting array has the given dimensions, and is filled with random numbers. The type of `y` is `double`, a 64-bit floating point array. To get arrays of other types, use the typecast functions.

The second syntax specifies the array dimensions as a vector, where each element in the vector specifies a dimension length:

      y = rand([d1,d2,...,dn]).

This syntax is more convenient for calling `rand` using a variable for the argument.

Finally, `rand` supports two additional forms that allow you to manipulate the state of the random number generator. The first retrieves the state

      y = rand('state')

which is a 625 length integer vector. The second form sets the state

      rand('state',y)

or alternately, you can reset the random number generator with

      rand('state',0)

# Example

The following example demonstrates an example of using the first form of the `rand` function.

    --> rand(2,2,2)

    ans =

    (:,:,1) =
        0.8539    0.1733
        0.0415    0.1300

    (:,:,2) =
        0.7163    0.5752
        0.5953    0.3728

The second example demonstrates the second form of the `rand` function.

    --> rand([2,2,2])

    ans =

    (:,:,1) =
        0.4992    0.2797
        0.6513    0.3209

    (:,:,2) =
        0.6244    0.7774
        0.0934    0.1820

The third example computes the mean and variance of a large number of uniform random numbers. Recall that the mean should be `1/2`, and the variance should be `1/12 ~ 0.083`.

    --> x = rand(1,10000);
    --> mean(x)

    ans =
        0.4952

    --> var(x)

    ans =
        0.0845

Now, we use the state manipulation functions of `rand` to exactly reproduce a random sequence. Note that unlike using `seed`, we can exactly control where the random number generator starts by saving the state.

    --> rand('state',0)    % restores us to startup conditions
    --> a = rand(1,3)      % random sequence 1

    a =
        0.3759    0.0183    0.9134

    --> b = rand('state'); % capture the state vector
    --> c = rand(1,3)      % random sequence 2

    c =
        0.3580    0.7604    0.8077

    --> rand('state',b);   % restart the random generator so...
    --> c = rand(1,3)      % we get random sequence 2 again

    c =
        0.3580    0.7604    0.8077