Random Numbers
Random number generation in Julia uses the Mersenne Twister library via MersenneTwister
objects. Julia has a global RNG, which is used by default. Other RNG types can be plugged in by inheriting the AbstractRNG
type; they can then be used to have multiple streams of random numbers. Besides MersenneTwister
, Julia also provides the RandomDevice
RNG type, which is a wrapper over the OS provided entropy.
Most functions related to random generation accept an optional AbstractRNG
as the first argument, rng
, which defaults to the global one if not provided. Morever, some of them accept optionally dimension specifications dims...
(which can be given as a tuple) to generate arrays of random values.
A MersenneTwister
or RandomDevice
RNG can generate random numbers of the following types: Float16
, Float32
, Float64
, BigFloat
, Bool
, Int8
, UInt8
, Int16
, UInt16
, Int32
, UInt32
, Int64
, UInt64
, Int128
, UInt128
, BigInt
(or complex numbers of those types). Random floating point numbers are generated uniformly in $[0, 1)$. As BigInt
represents unbounded integers, the interval must be specified (e.g. rand(big(1:6))
).
Random.srand
— Function.srand([rng=GLOBAL_RNG], seed) -> rng
srand([rng=GLOBAL_RNG]) -> rng
Reseed the random number generator: rng
will give a reproducible sequence of numbers if and only if a seed
is provided. Some RNGs don't accept a seed, like RandomDevice
. After the call to srand
, rng
is equivalent to a newly created object initialized with the same seed.
Examples
julia> srand(1234);
julia> x1 = rand(2)
2-element Array{Float64,1}:
0.590845
0.766797
julia> srand(1234);
julia> x2 = rand(2)
2-element Array{Float64,1}:
0.590845
0.766797
julia> x1 == x2
true
julia> rng = MersenneTwister(1234); rand(rng, 2) == x1
true
julia> MersenneTwister(1) == srand(rng, 1)
true
julia> rand(srand(rng), Bool) # not reproducible
true
julia> rand(srand(rng), Bool)
false
julia> rand(MersenneTwister(), Bool) # not reproducible either
true
Random.MersenneTwister
— Type.MersenneTwister(seed)
MersenneTwister()
Create a MersenneTwister
RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers. The seed
may be a non-negative integer or a vector of UInt32
integers. If no seed is provided, a randomly generated one is created (using entropy from the system). See the srand
function for reseeding an already existing MersenneTwister
object.
Examples
julia> rng = MersenneTwister(1234);
julia> x1 = rand(rng, 2)
2-element Array{Float64,1}:
0.5908446386657102
0.7667970365022592
julia> rng = MersenneTwister(1234);
julia> x2 = rand(rng, 2)
2-element Array{Float64,1}:
0.5908446386657102
0.7667970365022592
julia> x1 == x2
true
Random.RandomDevice
— Type.RandomDevice()
Create a RandomDevice
RNG object. Two such objects will always generate different streams of random numbers. The entropy is obtained from the operating system.
Base.rand
— Function.rand([rng=GLOBAL_RNG], [S], [dims...])
Pick a random element or array of random elements from the set of values specified by S
; S
can be
an indexable collection (for example
1:n
or['x','y','z']
),an
AbstractDict
orAbstractSet
object,a string (considered as a collection of characters), or
a type: the set of values to pick from is then equivalent to
typemin(S):typemax(S)
for integers (this is not applicable toBigInt
), and to $[0, 1)$ for floating point numbers;
S
defaults to Float64
(except when dims
is a tuple of integers, in which case S
must be specified).
Examples
julia> rand(Int, 2)
2-element Array{Int64,1}:
1339893410598768192
1575814717733606317
julia> rand(MersenneTwister(0), Dict(1=>2, 3=>4))
1=>2
The complexity of rand(rng, s::Union{AbstractDict,AbstractSet})
is linear in the length of s
, unless an optimized method with constant complexity is available, which is the case for Dict
, Set
and BitSet
. For more than a few calls, use rand(rng, collect(s))
instead, or either rand(rng, Dict(s))
or rand(rng, Set(s))
as appropriate.
Random.rand!
— Function.rand!([rng=GLOBAL_RNG], A, [S=eltype(A)])
Populate the array A
with random values. If S
is specified (S
can be a type or a collection, cf. rand
for details), the values are picked randomly from S
. This is equivalent to copyto!(A, rand(rng, S, size(A)))
but without allocating a new array.
Examples
julia> rng = MersenneTwister(1234);
julia> rand!(rng, zeros(5))
5-element Array{Float64,1}:
0.5908446386657102
0.7667970365022592
0.5662374165061859
0.4600853424625171
0.7940257103317943
Random.bitrand
— Function.bitrand([rng=GLOBAL_RNG], [dims...])
Generate a BitArray
of random boolean values.
Examples
julia> rng = MersenneTwister(1234);
julia> bitrand(rng, 10)
10-element BitArray{1}:
false
true
true
true
true
false
true
false
false
true
Base.randn
— Function.randn([rng=GLOBAL_RNG], [T=Float64], [dims...])
Generate a normally-distributed random number of type T
with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers. The Base
module currently provides an implementation for the types Float16
, Float32
, and Float64
(the default), and their Complex
counterparts. When the type argument is complex, the values are drawn from the circularly symmetric complex normal distribution.
Examples
julia> rng = MersenneTwister(1234);
julia> randn(rng, ComplexF64)
0.6133070881429037 - 0.6376291670853887im
julia> randn(rng, ComplexF32, (2, 3))
2×3 Array{Complex{Float32},2}:
-0.349649-0.638457im 0.376756-0.192146im -0.396334-0.0136413im
0.611224+1.56403im 0.355204-0.365563im 0.0905552+1.31012im
Random.randn!
— Function.randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A
Fill the array A
with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand
function.
Examples
julia> rng = MersenneTwister(1234);
julia> randn!(rng, zeros(5))
5-element Array{Float64,1}:
0.8673472019512456
-0.9017438158568171
-0.4944787535042339
-0.9029142938652416
0.8644013132535154
Random.randexp
— Function.randexp([rng=GLOBAL_RNG], [T=Float64], [dims...])
Generate a random number of type T
according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. The Base
module currently provides an implementation for the types Float16
, Float32
, and Float64
(the default).
Examples
julia> rng = MersenneTwister(1234);
julia> randexp(rng, Float32)
2.4835055f0
julia> randexp(rng, 3, 3)
3×3 Array{Float64,2}:
1.5167 1.30652 0.344435
0.604436 2.78029 0.418516
0.695867 0.693292 0.643644
Random.randexp!
— Function.randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A
Fill the array A
with random numbers following the exponential distribution (with scale 1).
Examples
julia> rng = MersenneTwister(1234);
julia> randexp!(rng, zeros(5))
5-element Array{Float64,1}:
2.4835053723904896
1.516703605376473
0.6044364871025417
0.6958665886385867
1.3065196315496677
Random.randjump
— Function.randjump(r::MersenneTwister, steps::Integer, len::Integer) -> Vector{MersenneTwister}
Create an array of size len
of initialized MersenneTwister
RNG objects. The first RNG object given as a parameter and following MersenneTwister
RNGs in the array are initialized such that a state of the RNG object in the array would be moved forward (without generating numbers) from a previous RNG object array element by steps
steps. One such step corresponds to the generation of two Float64
numbers. For each different value of steps
, a large polynomial has to be generated internally. One is already pre-computed for steps=big(10)^20
.
Random.randstring
— Function.randstring([rng=GLOBAL_RNG], [chars], [len=8])
Create a random string of length len
, consisting of characters from chars
, which defaults to the set of upper- and lower-case letters and the digits 0-9. The optional rng
argument specifies a random number generator, see Random Numbers.
Examples
julia> srand(0); randstring()
"Qgt7sUOP"
julia> randstring(MersenneTwister(0), 'a':'z', 6)
"oevnou"
julia> randstring("ACGT")
"TATCGGTC"
chars
can be any collection of characters, of type Char
or UInt8
(more efficient), provided rand
can randomly pick characters from it.
Random.randsubseq
— Function.randsubseq(A, p) -> Vector
Return a vector consisting of a random subsequence of the given array A
, where each element of A
is included (in order) with independent probability p
. (Complexity is linear in p*length(A)
, so this function is efficient even if p
is small and A
is large.) Technically, this process is known as "Bernoulli sampling" of A
.
Random.randsubseq!
— Function.randsubseq!(S, A, p)
Like randsubseq
, but the results are stored in S
(which is resized as needed).
Random.randperm
— Function.randperm([rng=GLOBAL_RNG,] n::Integer)
Construct a random permutation of length n
. The optional rng
argument specifies a random number generator (see Random Numbers). To randomly permute an arbitrary vector, see shuffle
or shuffle!
.
Examples
julia> randperm(MersenneTwister(1234), 4)
4-element Array{Int64,1}:
2
1
4
3
Random.randperm!
— Function.randperm!([rng=GLOBAL_RNG,] A::Array{<:Integer})
Construct in A
a random permutation of length length(A)
. The optional rng
argument specifies a random number generator (see Random Numbers). To randomly permute an arbitrary vector, see shuffle
or shuffle!
.
Examples
julia> randperm!(MersenneTwister(1234), Vector{Int}(undef, 4))
4-element Array{Int64,1}:
2
1
4
3
Random.randcycle
— Function.randcycle([rng=GLOBAL_RNG,] n::Integer)
Construct a random cyclic permutation of length n
. The optional rng
argument specifies a random number generator, see Random Numbers.
Examples
julia> randcycle(MersenneTwister(1234), 6)
6-element Array{Int64,1}:
3
5
4
6
1
2
Random.randcycle!
— Function.randcycle!([rng=GLOBAL_RNG,] A::Array{<:Integer})
Construct in A
a random cyclic permutation of length length(A)
. The optional rng
argument specifies a random number generator, see Random Numbers.
Examples
julia> randcycle!(MersenneTwister(1234), Vector{Int}(undef, 6))
6-element Array{Int64,1}:
3
5
4
6
1
2
Random.shuffle
— Function.shuffle([rng=GLOBAL_RNG,] v::AbstractArray)
Return a randomly permuted copy of v
. The optional rng
argument specifies a random number generator (see Random Numbers). To permute v
in-place, see shuffle!
. To obtain randomly permuted indices, see randperm
.
Examples
julia> rng = MersenneTwister(1234);
julia> shuffle(rng, Vector(1:10))
10-element Array{Int64,1}:
6
1
10
2
3
9
5
7
4
8
Random.shuffle!
— Function.shuffle!([rng=GLOBAL_RNG,] v::AbstractArray)
In-place version of shuffle
: randomly permute v
in-place, optionally supplying the random-number generator rng
.
Examples
julia> rng = MersenneTwister(1234);
julia> shuffle!(rng, Vector(1:16))
16-element Array{Int64,1}:
2
15
5
14
1
9
10
6
11
3
16
7
4
12
8
13