rng - Control random number generator - MATLAB (original) (raw)
Control random number generator
Syntax
Description
rng([seed](#mw%5Ff2bc0e65-a81b-407b-b52e-3c9af56c1157))
specifies the seed for the random number generator using the current generator algorithm.
- Specify
seed
as a nonnegative integer, such asrng(1)
, to initialize the random number generator with that seed. - Specify
seed
as"shuffle"
to initialize the generator seed based on the current time.
rng([seed](#mw%5Ff2bc0e65-a81b-407b-b52e-3c9af56c1157),[generator](#d126e1567772))
also specifies the algorithm for the random number generator to use. For example,rng(2,"philox")
initializes the Philox 4x32 generator with a seed of2
.
rng([generator](#d126e1567772))
specifies the algorithm for the random number generator to use with a seed of 0. This syntax is equivalent torng(0,generator)
. (since R2023b)
rng([s](#mw%5Fa6ff6cac-0eeb-4fcc-946d-5b7019e48296))
initializes the generator based on the settings contained in a structure s
with fieldsType
, Seed
, and State
. The structure s
must be a structure that is returned by a previous call tos = rng
or s = rng(__)
.
`t` = rng
returns the current random number generator settings in a structure t
with fieldsType
, Seed
, and State
.
`t` = rng(___)
returns the current random number generator settings in a structure t
before changing the settings using the specified arguments. You can specify the output argument with any of the input argument combinations in the previous syntaxes.
Examples
Use Default Generator Settings
Initialize the random number generator using the default generator algorithm and seed.
Show the default random number generator settings. In this case, the random number generator is using the Mersenne Twister algorithm with seed 0.
s = struct with fields: Type: 'twister' Seed: 0 State: [625x1 uint32]
Create a 4-by-4 matrix of uniformly distributed random numbers between 0 and 1.
r = 4×4
0.8147 0.6324 0.9575 0.9572
0.9058 0.0975 0.9649 0.4854
0.1270 0.2785 0.1576 0.8003
0.9134 0.5469 0.9706 0.1419
Starting in R2023b, you can set the default algorithm and seed from the MATLAB Preferences window. If you do not change the MATLAB preferences, then rng
uses the factory value of "twister"
for the Mersenne Twister generator with seed 0, as in previous releases.
Set and Restore Generator Settings
Specify the random number generator settings to make the results in this example repeatable. Set the generator seed to 2 and the algorithm to Mersenne Twister, and then save the generator settings.
s = struct with fields: Type: 'twister' Seed: 2 State: [625x1 uint32]
Create a 1-by-5 row vector of random values between 0 and 1.
x = 1×5
0.4360 0.0259 0.5497 0.4353 0.4204
Change the generator seed and algorithm, and create a new random row vector.
rng(1,"philox") xnew = rand(1,5)
xnew = 1×5
0.5361 0.2319 0.7753 0.2390 0.0036
Now restore the original generator settings and create a random vector. The result matches the original row vector x
created with the original generator.
xold = 1×5
0.4360 0.0259 0.5497 0.4353 0.4204
Input Arguments
seed
— Random number seed
nonnegative integer | "shuffle"
Random number seed, specified as a nonnegative integer less than2^32
or "shuffle"
. When you specifyseed
as "shuffle"
, the rng
function initializes the generator seed based on the current time, resulting in a different sequence of random numbers after each call to rng
.
generator
— Random number algorithm
"twister"
| "simdTwister"
| "combRecursive"
| "multFibonacci"
| "philox"
| "threefry"
Random number algorithm, specified as one of the options in the table. For more information on generator algorithms, see Creating and Controlling a Random Number Stream.
Value | Generator Name | Generator Keyword |
---|---|---|
"twister" | Mersenne Twister | mt19937ar |
"simdTwister" | SIMD-Oriented Fast Mersenne Twister | dsfmt19937 |
"combRecursive" | Combined Multiple Recursive | mrg32k3a |
"multFibonacci" | Multiplicative Lagged Fibonacci | mlfg6331_64 |
"philox" | Philox 4x32 generator with 10 rounds | philox4x32_10 |
"threefry" | Threefry 4x64 generator with 20 rounds | threefry4x64_20 |
For legacy generators used in MATLAB versions 4.0 and 5.0, use one of these options.
Value | Generator Name | Generator Keyword |
---|---|---|
"v4" | Legacy MATLAB version 4.0 generator | mcg16807 |
"v5uniform" | Legacy MATLAB version 5.0 uniform generator | swb2712 |
"v5normal" | Legacy MATLAB version 5.0 normal generator | shr3cong |
s
— Random number generator settings
structure
Random number generator settings, specified as a structure with fieldsType
, Seed
, and State
.
More About
Default Settings for Random Number Generator
- You can change the default algorithm and seed for the random number generator from the MATLABPreferences window. On the Home tab, in the Environment section, click
Preferences. Select > , and then select a different option for Default algorithm and select a different value for Default seed in the Random Number Generation preference. (since R2023b)
When you first start a MATLAB session or callrng("default")
, MATLAB initializes the random number generator using the default algorithm and seed that you have set in the MATLAB preferences. If you do not change the Random Number Generation preference, thenrng
uses the factory value of"twister"
for the Mersenne Twister generator with seed 0, as in previous releases. - If you use parallel workers (requires Parallel Computing Toolbox™),
rng("default")
initializes the Threefry 4x64 generator with 20 rounds and a seed value of 0. Changing the default generator settings in the MATLAB Preferences window does not affect the default behavior of the parallel workers. (since R2023a)
Reproducibility for Random Number Generator
Use rng("default")
at the start of your program if you want results to be repeatable within a MATLAB session. rng("default")
uses the default algorithm and seed that are specified in your MATLAB preferences. However, this command does not guarantee the same results between different MATLAB sessions with different preferences.
Instead, use rng(seed,generator)
or rng(generator)
at the start of your program if you want results to remain the same in future MATLAB releases or when the default algorithm and seed have been changed in your MATLAB preferences. For example, use rng("twister")
to use the Mersenne Twister generator with seed 0.
Pseudorandom Number Generator
The rng
function is a pseudorandom number generator, which creates a deterministic sequence of numbers that appear random. These numbers are predictable if the seed and the deterministic algorithm of the generator are known. While not truly random, the generated numbers pass various statistical tests of randomness, satisfying the independent and identically distributed (i.i.d.) condition, and justifying the name pseudorandom.
Tips
- When you perform parallel processing, do not use
rng("shuffle")
to set the random number stream on different workers for independent streams because it seeds the random number generator based on the current time. Therng
function uses the same seed when the command is sent to multiple workers simultaneously, such as inside aparfor
job. For independent streams on the workers, use the default behavior or consider using a unique substream on each worker using RandStream. - When you perform parallel processing, the default random number generators on the MATLAB client and MATLAB workers are different. By default, the MATLAB client uses the Mersenne Twister generator with seed 0 and the MATLAB workers use the Threefry 4x64 generator with 20 rounds with seed 0. Changing the default generator settings in the MATLAB preferences affects only the default behavior of the client and does not affect the default behavior of the parallel workers. If you need to generate the same random stream of numbers on the client and workers, you can use
rng
with the same generator algorithm and seed (or consider using RandStream with the same generator algorithm, seed, and normal transformation algorithm). For more information, see Control Random Number Streams on Workers (Parallel Computing Toolbox). - To use
rng
instead of therand
orrandn
functions with the"seed"
,"state"
, or"twister"
inputs, see Replace Discouraged Syntaxes of rand and randn.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
- Only the
"twister"
,"v5normal"
, and"v4"
generators are supported. - The generated code for
rng("shuffle")
might produce different seeds than MATLAB produces. - For a MEX target:
- If extrinsic calls are disabled or
rng
is called inside aparfor
-loop, the output ofrng
in the MEX function is not compatible with therng
function in MATLAB. You cannot pass the output ofs = rng
from the MEX function torng
in MATLAB. - If extrinsic calls are enabled and
rng
is not called from inside aparfor
-loop, onlyrng
can access the data in the structure thatrng
returns. - If extrinsic calls are enabled and
rng
is not called from inside aparfor
-loop, generated MEX files use the same random number state as MATLAB in serial code. Otherwise, the generated MEX code and standalone code maintain their own random number state that is initialized to the same state as MATLAB.
- If extrinsic calls are disabled or
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 R2011a
R2023b: Specify random number algorithm without specifying seed
Use the new syntax rng(generator)
to specify the algorithm for the random number generator to use. This syntax allows you to set the random number algorithm without specifying the seed, where rng
uses a seed of 0. This syntax is equivalent to rng(0,generator)
. For example,rng("philox")
initializes the Philox 4x32 generator with a seed of 0.
R2023b: Change default algorithm and seed for random number generator
You can change the default algorithm and seed for the random number generator from the MATLABPreferences window. On the Home tab, in the Environment section, click Preferences. Select > , and then select a different option for Default algorithm and select a different value for Default seed in the Random Number Generation preference.
When you first start a MATLAB session or call rng("default")
, MATLAB initializes the random number generator using the default algorithm and seed that you have set in the MATLAB preferences. If you do not change the Random Number Generation preference, then rng
uses the factory value of"twister"
for the Mersenne Twister generator with seed 0, as in previous releases.
To access and modify settings for the random number generator programmatically, you can access thematlab.general.randomnumbers
settings using the rootSettingsGroup
object returned by the settings function. For example, show the default algorithm and seed that you have set for the random number generator.
s = settings; s.matlab.general.randomnumbers.DefaultAlgorithm s.matlab.general.randomnumbers.DefaultSeed
When you perform parallel processing (requires Parallel Computing Toolbox), by default, the MATLAB client uses the Mersenne Twister random number generator with seed 0 and the MATLAB workers use the Threefry 4x64 generator with 20 rounds with seed 0. Changing the default generator settings in the MATLAB Preferences window or using thematlab.general.randomnumbers
settings affects only the default behavior of the client and does not affect the default behavior of the parallel workers.
R2023a: On MATLAB parallel workers, rng("default")
sets random number generator settings to worker default
When you use the syntax rng("default")
on MATLAB parallel workers (requires Parallel Computing Toolbox), MATLAB resets the random number generator settings to the worker default values. The default corresponds to the Threefry 4x64 generator with 20 rounds and a seed value of 0.
In previous releases, when you use rng("default")
on parallel workers, MATLAB changes the worker random number generator settings to the client default values. The default corresponds to the Mersenne Twister generator with a seed value of 0.
See Also
Functions
- rand | randi | randn | randperm | RandStream.create