RandStream - Random number stream - MATLAB (original) (raw)

Description

RandStream creates a random number stream using a specified pseudorandom number generator algorithm.

You can generate pseudorandom numbers in MATLAB® from one or more random number streams. The simplest way to generate arrays of random numbers is to use the rand, randi, randn, and randperm functions. These functions all rely on the same stream of uniformly distributed random numbers, known as the global stream. Changing the global stream can involve RandStream, but it does not have to. If you create a stream using RandStream, you can use RandStream.setGlobalStream to make it the global stream. However, the rng function provides a simpler interface to create a global stream that is sufficient for most use cases.

You can also use RandStream to create streams and then userand, randi, randn, orrandperm to generate random numbers from these streams. The generated random numbers are separate from those drawn from the global stream or from other streams. For details, see Object Functions.

Creation

Use the following syntaxes to create a single random number stream. If you want to create multiple independent streams simultaneously, use the RandStream.create function.

Syntax

Description

`s` = RandStream([gentype](#mw%5Fcc34b6ad-c7e6-4943-b21b-7d7310a4dd52)) creates a random number stream that uses the uniform pseudorandom number generator algorithm specified by gentype.

example

`s` = RandStream([gentype](#mw%5Fcc34b6ad-c7e6-4943-b21b-7d7310a4dd52),[Name,Value](#namevaluepairarguments)) also controls properties of the stream using one or more optionalName,Value pair arguments.

example

Input Arguments

expand all

gentype — Random number generator algorithm

'mt19937ar' | 'dsfmt19937' | 'mcg16807' | ...

Random number generator algorithm, specified as a character vector or string scalar naming a random number generator. MATLAB offers several generator algorithms. The following table summarizes the names and key properties of the available generator algorithms. Some generator algorithms support multiple streams and substreams to create sets of random numbers that are mutually independent. For more information, see Creating and Controlling a Random Number Stream.

Name Generator Multiple Stream and Substream Support Approximate Period In Full Precision
'mt19937ar' Mersenne Twister No 219937-1
'dsfmt19937' SIMD-Oriented Fast Mersenne Twister No 219937-1
'mlfg6331_64' Multiplicative lagged Fibonacci generator Yes 2124 (251 streams of length 272)
'mrg32k3a' Combined multiple recursive generator Yes 2191 (263 streams of length 2127)
'philox4x32_10' Philox 4x32 generator with 10 rounds Yes 2193 (264 streams of length 2129)
'threefry4x64_20' Threefry 4x64 generator with 20 rounds Yes 2514 (2256 streams of length 2258)
'shr3cong' Shift-register generator summed with linear congruential generator No 264
'swb2712' Modified subtract with borrow generator No 21492
'mcg16807' Multiplicative congruential generator No 231-2

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: s = RandStream('mt19937ar','Seed',15,'NormalTransform','Polar')

Seed — Random number seed

0 (default) | nonnegative integer | 'shuffle'

Random number seed, specified as the comma-separated pair consisting of'Seed' and a nonnegative integer or'shuffle'. The seed specifies the starting point for the algorithm to generate random numbers. 'shuffle' creates a seed based on the current time. If you specify an integer, it must be between 0 and 232 − 1.

Specify the generator seed as an initialization step when creating a stream at MATLAB startup or before running a simulation. To reproduce a stream, use the same seed every time. While using multiple seeds will create multiple sequences of random numbers, there is no guarantee that the different sequences are statistically independent. In situations where this is important, specify the Substream property or useRandStream.create to create streams that are statistically independent.

NormalTransform — Normal transformation algorithm

'Ziggurat' | 'Polar' | 'Inversion'

Transformation algorithm to generate normally distributed random numbers from the random number stream using randn, specified as the comma-separated pair consisting of'NormalTransform' and one of the algorithm names'Ziggurat','Polar', or'Inversion'. For more information, see Creating and Controlling a Random Number Stream.

Properties

expand all

A random number stream s has properties that control its behavior. Access a property using p = s.Property and modify one usings.Property = p. To save and restore all properties of a streams, you can use A = get(s) andset(s,A), respectively. This list describes the properties ofRandStream.

Type — Random number generator algorithm

'mt19937ar' | 'dsfmt19937' | 'mcg16807' | ...

This property is read-only.

Random number generator algorithm used by the stream. See the table of generator algorithms for a summary of generators and their properties.

Not all generators algorithms support multiple streams. For some generators, you can create multiple streams and substreams that are statistically independent.

Data Types: char

Seed — Random number seed

0 (default) | nonnegative integer

This property is read-only.

Random number seed used to create the stream, returned as a nonnegative integer.

Data Types: uint32

NumStreams — Number of streams

1 (default) | positive integer

This property is read-only.

Number of streams in the group in which the current stream was created, returned as a positive integer.

Data Types: uint64

StreamIndex — Stream index

1 (default) | positive integer

This property is read-only.

Index of the current stream from among the group of streams with which it was created, returned as a positive integer.

Data Types: uint64

State — Current internal state

vector of integers

Current internal state of the generator, specified as a vector of integers. The size of the state vector depends on the generator algorithm. When you set this property, the value you assign to s.State must be a value read froms.State previously. Use reset to return a stream to its initial state without having previously read from the State property. Saving and restoring the internal state of the generator with the State property allows you to reproduce a sequence of random numbers.

The internal state determines the sequence of random numbers produced by the random number stream s. Every time you generate random numbers from a single stream, the state of the generator in the stream is transformed to create successive values that are statistically independent and identically distributed.

Note

Only restore the state of a random number stream, or reset a stream, to reproduce results from the stream.

Data Types: uint32

Substream — Substream Index

1 (default) | positive integer

Index of the substream to which the stream is currently set.

For some generator types, you can create different substreams from a random stream. Values generated from different substreams are mutually independent. See the table ofgenerator algorithms for generators that support substreams.

Data Types: double

NormalTransform — Normal transformation algorithm

'Ziggurat' (default) | 'Polar' | 'Inversion'

Transformation algorithm to generate normally distributed pseudorandom values usingrandn.

Data Types: char

Antithetic — Antithetic values

false (default) | true

Whether s generates antithetic pseudorandom values, specified as logical true (1) or false (0). Antithetic values are the default generated pseudorandom values with uniform distribution subtracted from 1.

Data Types: logical

FullPrecision — Full precision generation

true (default) | false

Whether s generates values using its full precision, specified as logical true (1) or false (0). Some generators can create pseudorandom values faster, but with fewer random bits, if FullPrecision isfalse.

Data Types: logical

Object Functions

By default, random number generation functions, such as rand, use the global random number stream. To specify a different stream, create a RandStream object and pass it as the first input argument. For instance, create a 4-by-1 vector of random numbers using the SIMD-Oriented Fast Mersenne Twister.

s = RandStream('dsfmt19937'); r = rand(s,4,1);

These functions accept a RandStream object:

rand Uniformly distributed random numbers Supported syntaxes, where s is a RandStream object:X = rand(s) X = rand(s,n) X = rand(s,sz1,...,szN) X = rand(s,sz) X = rand(s,__,typename) X = rand(s,__,'like',p)For details on other input arguments, see rand, randi, and randn.
randi Uniformly distributed pseudorandom integers
randn Normally distributed random numbers
randperm Random permutation of integers Supported syntaxes, where s is a RandStream object:p = randperm(s,n) p = randperm(s,n,k) For details on other input arguments, see randperm.

Other object functions of RandStream are:

Examples

collapse all

Create and Use Stream

Create a random number stream using the SIMD-Oriented Fast Mersenne Twister.

s = RandStream('dsfmt19937')

s = dsfmt19937 random stream Seed: 0 NormalTransform: Ziggurat

Use the stream to generate five random numbers.

ans = 1×5

0.0306    0.2131    0.2990    0.3811    0.8635

Initialize Generator Seed

Create a random number stream using a generator seed based on the current time. It is usually not desirable to do this more than once per MATLAB® session as it may affect the statistical properties of the random numbers MATLAB produces.

s = RandStream('mt19937ar','Seed','shuffle');

Use the stream to create a 3-by-3 matrix of random values with uniform distribution between 0 and 1.

X1 = 3×3

0.5361    0.9162    0.6395
0.6835    0.9749    0.5718
0.3380    0.3897    0.7105

Create another five random numbers from the stream.

X2 = 1×5

0.7247    0.5140    0.4598    0.5440    0.6531

Size and Data Type Defined by Existing Array

Create a 2-by-3 matrix of single-precision numbers.

p = single([0.1 -3 2.5; 1.2 -3.4 6]);

Create a random number stream whose seed is zero.

s = RandStream('mcg16807','Seed',0);

Use the stream to generate an array of random numbers that is the same size and data type as p.

z = rand(s,size(p),'like',p)

z = 2x3 single matrix

0.2190    0.6789    0.9347
0.0470    0.6793    0.3835

Restore State to Reproduce Output

Create a random number stream whose seed is zero.

s = RandStream('mcg16807','Seed',0);

Generate five random numbers from the stream. Every time you generate a number from the stream, the generator algorithm transforms the internal state such that the next generated number is independent and identically distributed from the previous number.

u1 = 1×5

0.2190    0.0470    0.6789    0.6793    0.9347

Save the current state of the generator. Generate another five random numbers.

savedState = s.State; u2 = rand(s,1,5)

u2 = 1×5

0.3835    0.5194    0.8310    0.0346    0.0535

To reproduce the last outcome of five random numbers, restore the generator state to the saved state.

s.State = savedState; u3 = rand(s,1,5)

u3 = 1×5

0.3835    0.5194    0.8310    0.0346    0.0535

Only read and write the generator state to reproduce a specific outcome from the stream.

Reset a Random Number Stream

Create a random number stream whose seed is three. Use the stream to generate eight random numbers.

stream = RandStream('dsfmt19937','Seed',3); z = rand(stream,1,8)

z = 1×8

0.2550    0.8753    0.0908    0.1143    0.3617    0.8210    0.8444    0.6189

Reset the random number stream to its initial state with seed equal to three. Reproduce the eight random numbers that were generated.

reset(stream,3); z = rand(stream,1,8)

z = 1×8

0.2550    0.8753    0.0908    0.1143    0.3617    0.8210    0.8444    0.6189

Resetting a stream's seed can invalidate independence with other streams. Only reset a stream to reproduce results from the stream.

Set Global and Local Streams

Create two random number streams. Set the first stream as a global stream by using RandStream.setGlobalStream.

globalStream = RandStream('mlfg6331_64','NormalTransform','Polar')

globalStream = mlfg6331_64 random stream Seed: 0 NormalTransform: Polar

RandStream.setGlobalStream(globalStream);

To show the current global stream, use RandStream.getGlobalStream.

RandStream.getGlobalStream

ans = mlfg6331_64 random stream (current global stream) Seed: 0 NormalTransform: Polar

Create a second stream myStream that acts separately from the new global stream that you created.

myStream = RandStream('dsfmt19937','NormalTransform','Inversion')

myStream = dsfmt19937 random stream Seed: 0 NormalTransform: Inversion

Generate three random numbers from the global stream. Generate another three random numbers from the local stream myStream that you created.

ans = 1×3

0.8715    1.0588   -0.6956

ans = 1×3

-1.8723 -0.7956 -0.5273

When you call the functions rand, randn, and randi without myStream, they draw from the global stream and will not affect the results of calling them with myStream.

Random Number Generator Using Substreams

For some generator types, you can create different substreams from a random stream. Values generated from different substreams are mutually independent.

For instance, create a random number stream using a combined multiple recursive generator.

s = RandStream('mrg32k3a');

To reposition a stream to a particular substream, set its Substream property. For instance, generate random numbers in a loop. Position the random number stream to the beginning of a different substream before each iteration of the loop. Generate 3 mutually independent sets of 5 random numbers.

for i = 1:3 s.Substream = i; z = rand(s,1,5) end

z = 1×5

0.7270    0.4522    0.9387    0.2360    0.0277

z = 1×5

0.5582    0.8527    0.7733    0.0633    0.2788

z = 1×5

0.1666    0.2924    0.7728    0.8391    0.5107

To reproduce the second set of 5 random numbers, reposition the stream to the corresponding substream.

s.Substream = 2; z = rand(s,1,5)

z = 1×5

0.5582    0.8527    0.7733    0.0633    0.2788

More About

expand all

Random Number Stream

A random number stream is a source for a sequence of_pseudorandom_ numbers generated by deterministic algorithms. A pseudorandom sequence is an approximation to a theoretical sequence of random numbers whose distribution satisfies the independent and identically distributed (i.i.d.) condition, but in practice, a deterministic algorithm cannot generate i.i.d sequences. Instead, the algorithms generate sequences that pass statistical tests on their distribution and correlation to show that they are good approximations.

Extended Capabilities

Thread-Based Environment

Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

Version History

Introduced in R2008b