Navigation

Operators and Keywords

Function List:

C++ API

: rand (n)
: rand (m, n, …)
: rand ([m n …])
: v = rand ("state")
: rand ("state", v)
: rand ("state", "reset")
: v = rand ("seed")
: rand ("seed", v)
: rand ("seed", "reset")
: rand (…, "single")
: rand (…, "double")

Return a matrix with random elements uniformly distributed on the interval (0, 1).

The arguments are handled the same as the arguments for eye.

You can query the state of the random number generator using the form

v = rand ("state")

This returns a column vector v of length 625. Later, you can restore the random number generator to the state v using the form

rand ("state", v)

You may also initialize the state vector from an arbitrary vector of length ≤ 625 for v. This new state will be a hash based on the value of v, not v itself.

By default, the generator is initialized from /dev/urandom if it is available, otherwise from CPU time, wall clock time, and the current fraction of a second. Note that this differs from MATLAB, which always initializes the state to the same state at startup. To obtain behavior comparable to MATLAB, initialize with a deterministic state vector in Octave’s startup files (see ‘Startup Files’).

To compute the pseudo-random sequence, rand uses the Mersenne Twister with a period of 2^{19937}-1 (See M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator, ACM Trans. on Modeling and Computer Simulation Vol. 8, No. 1, pp. 3–30, January 1998, http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html). Do not use for cryptography without securely hashing several returned values together, otherwise the generator state can be learned after reading 624 consecutive values.

Older versions of Octave used a different random number generator. The new generator is used by default as it is significantly faster than the old generator, and produces random numbers with a significantly longer cycle time. However, in some circumstances it might be desirable to obtain the same random sequences as produced by the old generators. To do this the keyword "seed" is used to specify that the old generators should be used, as in

rand ("seed", val)

which sets the seed of the generator to val. The seed of the generator can be queried with

s = rand ("seed")

However, it should be noted that querying the seed will not cause rand to use the old generators, only setting the seed will. To cause rand to once again use the new generators, the keyword "state" should be used to reset the state of the rand.

The state or seed of the generator can be reset to a new random value using the "reset" keyword.

The class of the value returned can be controlled by a trailing "double" or "single" argument. These are the only valid classes.

See also: randn, rande, randg, randp.

Package: octave