Random number generation in Julia uses theXoshiro256++ algorithm by default, with per-Task
state. Other RNG types can be plugged in by inheriting theAbstractRNG
type; they can then be used to obtain multiple streams of random numbers.
The PRNGs (pseudorandom number generators) exported by theRandom
package are:
TaskLocalRNG
: a token that represents use of the currently active Task-local stream, deterministically seeded from the parent task, or byRandomDevice
(with system randomness) at program startXoshiro
: generates a high-quality stream of random numbers with a small state vector and high performance using the Xoshiro256++ algorithmRandomDevice
: for OS-provided entropy. This may be used for cryptographically secure random numbers (CS(P)RNG).MersenneTwister
: an alternate high-quality PRNG which was the default in older versions of Julia, and is also quite fast, but requires much more space to store the state vector and generate a random sequence.Most functions related to random generation accept an optionalAbstractRNG
object as first argument. Some also accept dimension specificationsdims...
(which can also be given as a tuple) to generate arrays of random values. In a multi-threaded program, you should generally use different RNG objects from different threads or tasks in order to be thread-safe. However, the default RNG is thread-safe as of Julia 1.3 (using a per-thread RNG up to version 1.6, and per-task thereafter).
The provided RNGs can generate uniform 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)$. AsBigInt
represents unbounded integers, the interval must be specified (e.g.rand(big.(1:6))
).
Additionally, normal and exponential distributions are implemented for someAbstractFloat
andComplex
types, seerandn
andrandexp
for details.
To generate random numbers from other distributions, see theDistributions.jl package.
Because the precise way in which random numbers are generated is considered an implementation detail, bug fixes and speed improvements may change the stream of numbers that are generated after a version change. Relying on a specific seed or generated stream of numbers during unit testing is thus discouraged - consider testing properties of the methods in question instead.
Random.Random
—ModuleRandom
Support for generating random numbers. Providesrand
,randn
,AbstractRNG
,MersenneTwister
, andRandomDevice
.
Base.rand
—Functionrand([rng=default_rng()], [S], [dims...])
Pick a random element or array of random elements from the set of values specified byS
;S
can be
an indexable collection (for example1:9
or('x', "y", :z)
)
anAbstractDict
orAbstractSet
object
a string (considered as a collection of characters), or
a type from the list below, corresponding to the specified set of values
concrete integer types sample fromtypemin(S):typemax(S)
(exceptingBigInt
which is not supported)
concrete floating point types sample from[0, 1)
concrete complex typesComplex{T}
ifT
is a sampleable type take their real and imaginary components independently from the set of values corresponding toT
, but are not supported ifT
is not sampleable.
all<:AbstractChar
types sample from the set of valid Unicode scalars
a user-defined type and set of values; for implementation guidance please seeHooking into theRandom
API
a tuple type of known size and where each parameter ofS
is itself a sampleable type; return a value of typeS
. Note that tuple types such asTuple{Vararg{T}}
(unknown size) andTuple{1:2}
(parameterized with a value) are not supported
aPair
type, e.g.Pair{X, Y}
such thatrand
is defined forX
andY
, in which case random pairs are produced.
S
defaults toFloat64
. When only one argument is passed besides the optionalrng
and is aTuple
, it is interpreted as a collection of values (S
) and not asdims
.
See alsorandn
for normally distributed numbers, andrand!
andrandn!
for the in-place equivalents.
Support forS
as a tuple requires at least Julia 1.1.
Support forS
as aTuple
type requires at least Julia 1.11.
Examples
julia> rand(Int, 2)2-element Array{Int64,1}: 1339893410598768192 1575814717733606317julia> using Randomjulia> rand(Xoshiro(0), Dict(1=>2, 3=>4))3 => 4julia> rand((2, 3))3julia> rand(Float64, (2, 3))2×3 Array{Float64,2}: 0.999717 0.0143835 0.540787 0.696556 0.783855 0.938235
The complexity ofrand(rng, s::Union{AbstractDict,AbstractSet})
is linear in the length ofs
, unless an optimized method with constant complexity is available, which is the case forDict
,Set
and denseBitSet
s. For more than a few calls, userand(rng, collect(s))
instead, or eitherrand(rng, Dict(s))
orrand(rng, Set(s))
as appropriate.
Random.rand!
—Functionrand!([rng=default_rng()], A, [S=eltype(A)])
Populate the arrayA
with random values. IfS
is specified (S
can be a type or a collection, cf.rand
for details), the values are picked randomly fromS
. This is equivalent tocopyto!(A, rand(rng, S, size(A)))
but without allocating a new array.
Examples
julia> rand!(Xoshiro(123), zeros(5))5-element Vector{Float64}: 0.521213795535383 0.5868067574533484 0.8908786980927811 0.19090669902576285 0.5256623915420473
Random.bitrand
—Functionbitrand([rng=default_rng()], [dims...])
Generate aBitArray
of random boolean values.
Examples
julia> bitrand(Xoshiro(123), 10)10-element BitVector: 0 1 0 1 0 1 0 0 1 1
Base.randn
—Functionrandn([rng=default_rng()], [T=Float64], [dims...])
Generate a normally-distributed random number of typeT
with mean 0 and standard deviation 1. Given the optionaldims
argument(s), generate an array of sizedims
of such numbers. Julia's standard library supportsrandn
for any floating-point type that implementsrand
, e.g. theBase
typesFloat16
,Float32
,Float64
(the default), andBigFloat
, along with theirComplex
counterparts.
(WhenT
is complex, the values are drawn from the circularly symmetric complex normal distribution of variance 1, corresponding to real and imaginary parts having independent normal distribution with mean zero and variance1/2
).
See alsorandn!
to act in-place.
Examples
Generating a single random number (with the defaultFloat64
type):
julia> randn()-0.942481877315864
Generating a matrix of normal random numbers (with the defaultFloat64
type):
julia> randn(2,3)2×3 Matrix{Float64}: 1.18786 -0.678616 1.49463 -0.342792 -0.134299 -1.45005
Setting up of the random number generatorrng
with a user-defined seed (for reproducible numbers) and using it to generate a randomFloat32
number or a matrix ofComplexF32
random numbers:
julia> using Randomjulia> rng = Xoshiro(123);julia> randn(rng, Float32)-0.6457307f0julia> randn(rng, ComplexF32, (2, 3))2×3 Matrix{ComplexF32}: -1.03467-1.14806im 0.693657+0.056538im 0.291442+0.419454im -0.153912+0.34807im 1.0954-0.948661im -0.543347-0.0538589im
Random.randn!
—Functionrandn!([rng=default_rng()], A::AbstractArray) -> A
Fill the arrayA
with normally-distributed (mean 0, standard deviation 1) random numbers. Also see therand
function.
Examples
julia> randn!(Xoshiro(123), zeros(5))5-element Vector{Float64}: -0.6457306721039767 -1.4632513788889214 -1.6236037455860806 -0.21766510678354617 0.4922456865251828
Random.randexp
—Functionrandexp([rng=default_rng()], [T=Float64], [dims...])
Generate a random number of typeT
according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. TheBase
module currently provides an implementation for the typesFloat16
,Float32
, andFloat64
(the default).
Examples
julia> rng = Xoshiro(123);julia> randexp(rng, Float32)1.1757717f0julia> randexp(rng, 3, 3)3×3 Matrix{Float64}: 1.37766 0.456653 0.236418 3.40007 0.229917 0.0684921 0.48096 0.577481 0.71835
Random.randexp!
—Functionrandexp!([rng=default_rng()], A::AbstractArray) -> A
Fill the arrayA
with random numbers following the exponential distribution (with scale 1).
Examples
julia> randexp!(Xoshiro(123), zeros(5))5-element Vector{Float64}: 1.1757716836348473 1.758884569451514 1.0083623637301151 0.3510644315565272 0.6348266443720407
Random.randstring
—Functionrandstring([rng=default_rng()], [chars], [len=8])
Create a random string of lengthlen
, consisting of characters fromchars
, which defaults to the set of upper- and lower-case letters and the digits 0-9. The optionalrng
argument specifies a random number generator, seeRandom Numbers.
Examples
julia> Random.seed!(3); randstring()"Lxz5hUwn"julia> randstring(Xoshiro(3), 'a':'z', 6)"iyzcsm"julia> randstring("ACGT")"TGCTCCTC"
chars
can be any collection of characters, of typeChar
orUInt8
(more efficient), providedrand
can randomly pick characters from it.
Random.randsubseq
—Functionrandsubseq([rng=default_rng(),] A, p) -> Vector
Return a vector consisting of a random subsequence of the given arrayA
, where each element ofA
is included (in order) with independent probabilityp
. (Complexity is linear inp*length(A)
, so this function is efficient even ifp
is small andA
is large.) Technically, this process is known as "Bernoulli sampling" ofA
.
Examples
julia> randsubseq(Xoshiro(123), 1:8, 0.3)2-element Vector{Int64}: 4 7
Random.randsubseq!
—Functionrandsubseq!([rng=default_rng(),] S, A, p)
Likerandsubseq
, but the results are stored inS
(which is resized as needed).
Examples
julia> S = Int64[];julia> randsubseq!(Xoshiro(123), S, 1:8, 0.3)2-element Vector{Int64}: 4 7julia> S2-element Vector{Int64}: 4 7
Random.randperm
—Functionrandperm([rng=default_rng(),] n::Integer)
Construct a random permutation of lengthn
. The optionalrng
argument specifies a random number generator (seeRandom Numbers). The element type of the result is the same as the type ofn
.
To randomly permute an arbitrary vector, seeshuffle
orshuffle!
.
In Julia 1.1randperm
returns a vectorv
witheltype(v) == typeof(n)
while in Julia 1.0eltype(v) == Int
.
Examples
julia> randperm(Xoshiro(123), 4)4-element Vector{Int64}: 1 4 2 3
Random.randperm!
—Functionrandperm!([rng=default_rng(),] A::Array{<:Integer})
Construct inA
a random permutation of lengthlength(A)
. The optionalrng
argument specifies a random number generator (seeRandom Numbers). To randomly permute an arbitrary vector, seeshuffle
orshuffle!
.
Examples
julia> randperm!(Xoshiro(123), Vector{Int}(undef, 4))4-element Vector{Int64}: 1 4 2 3
Random.randcycle
—Functionrandcycle([rng=default_rng(),] n::Integer)
Construct a random cyclic permutation of lengthn
. The optionalrng
argument specifies a random number generator, seeRandom Numbers. The element type of the result is the same as the type ofn
.
Here, a "cyclic permutation" means that all of the elements lie within a single cycle. Ifn > 0
, there are$(n-1)!$ possible cyclic permutations, which are sampled uniformly. Ifn == 0
,randcycle
returns an empty vector.
randcycle!
is an in-place variant of this function.
In Julia 1.1 and above,randcycle
returns a vectorv
witheltype(v) == typeof(n)
while in Julia 1.0eltype(v) == Int
.
Examples
julia> randcycle(Xoshiro(123), 6)6-element Vector{Int64}: 5 4 2 6 3 1
Random.randcycle!
—Functionrandcycle!([rng=default_rng(),] A::Array{<:Integer})
Construct inA
a random cyclic permutation of lengthn = length(A)
. The optionalrng
argument specifies a random number generator, seeRandom Numbers.
Here, a "cyclic permutation" means that all of the elements lie within a single cycle. IfA
is nonempty (n > 0
), there are$(n-1)!$ possible cyclic permutations, which are sampled uniformly. IfA
is empty,randcycle!
leaves it unchanged.
randcycle
is a variant of this function that allocates a new vector.
Examples
julia> randcycle!(Xoshiro(123), Vector{Int}(undef, 6))6-element Vector{Int64}: 5 4 2 6 3 1
Random.shuffle
—Functionshuffle([rng=default_rng(),] v::AbstractArray)
Return a randomly permuted copy ofv
. The optionalrng
argument specifies a random number generator (seeRandom Numbers). To permutev
in-place, seeshuffle!
. To obtain randomly permuted indices, seerandperm
.
Examples
julia> shuffle(Xoshiro(123), Vector(1:10))10-element Vector{Int64}: 5 4 2 3 6 10 8 1 9 7
Random.shuffle!
—Functionshuffle!([rng=default_rng(),] v::AbstractArray)
In-place version ofshuffle
: randomly permutev
in-place, optionally supplying the random-number generatorrng
.
Examples
julia> shuffle!(Xoshiro(123), Vector(1:10))10-element Vector{Int64}: 5 4 2 3 6 10 8 1 9 7
Random.default_rng
—FunctionRandom.default_rng() -> rng
Return the default global random number generator (RNG), which is used byrand
-related functions when no explicit RNG is provided.
When theRandom
module is loaded, the default RNG israndomly seeded, viaRandom.seed!()
: this means that each time a new julia session is started, the first call torand()
produces a different result, unlessseed!(seed)
is called first.
It is thread-safe: distinct threads can safely callrand
-related functions ondefault_rng()
concurrently, e.g.rand(default_rng())
.
The type of the default RNG is an implementation detail. Across different versions of Julia, you should not expect the default RNG to always have the same type, nor that it will produce the same stream of random numbers for a given seed.
This function was introduced in Julia 1.3.
Random.seed!
—Functionseed!([rng=default_rng()], seed) -> rngseed!([rng=default_rng()]) -> rng
Reseed the random number generator:rng
will give a reproducible sequence of numbers if and only if aseed
is provided. Some RNGs don't accept a seed, likeRandomDevice
. After the call toseed!
,rng
is equivalent to a newly created object initialized with the same seed. The types of accepted seeds depend on the type ofrng
, but in general, integer seeds should work.
Ifrng
is not specified, it defaults to seeding the state of the shared task-local generator.
Examples
julia> Random.seed!(1234);julia> x1 = rand(2)2-element Vector{Float64}: 0.32597672886359486 0.5490511363155669julia> Random.seed!(1234);julia> x2 = rand(2)2-element Vector{Float64}: 0.32597672886359486 0.5490511363155669julia> x1 == x2truejulia> rng = Xoshiro(1234); rand(rng, 2) == x1truejulia> Xoshiro(1) == Random.seed!(rng, 1)truejulia> rand(Random.seed!(rng), Bool) # not reproducibletruejulia> rand(Random.seed!(rng), Bool) # not reproducible eitherfalsejulia> rand(Xoshiro(), Bool) # not reproducible eithertrue
Random.AbstractRNG
—TypeAbstractRNG
Supertype for random number generators such asMersenneTwister
andRandomDevice
.
Random.TaskLocalRNG
—TypeTaskLocalRNG
TheTaskLocalRNG
has state that is local to its task, not its thread. It is seeded upon task creation, from the state of its parent task, but without advancing the state of the parent's RNG.
As an upside, theTaskLocalRNG
is pretty fast, and permits reproducible multithreaded simulations (barring race conditions), independent of scheduler decisions. As long as the number of threads is not used to make decisions on task creation, simulation results are also independent of the number of available threads / CPUs. The random stream should not depend on hardware specifics, up to endianness and possibly word size.
Using or seeding the RNG of any other task than the one returned bycurrent_task()
is undefined behavior: it will work most of the time, and may sometimes fail silently.
When seedingTaskLocalRNG()
withseed!
, the passed seed, if any, may be any integer.
SeedingTaskLocalRNG()
with a negative integer seed requires at least Julia 1.11.
Task creation no longer advances the parent task's RNG state as of Julia 1.10.
Random.Xoshiro
—TypeXoshiro(seed::Union{Integer, AbstractString})Xoshiro()
Xoshiro256++ is a fast pseudorandom number generator described by David Blackman and Sebastiano Vigna in "Scrambled Linear Pseudorandom Number Generators", ACM Trans. Math. Softw., 2021. Reference implementation is available at https://prng.di.unimi.it
Apart from the high speed, Xoshiro has a small memory footprint, making it suitable for applications where many different random states need to be held for long time.
Julia's Xoshiro implementation has a bulk-generation mode; this seeds new virtual PRNGs from the parent, and uses SIMD to generate in parallel (i.e. the bulk stream consists of multiple interleaved xoshiro instances). The virtual PRNGs are discarded once the bulk request has been serviced (and should cause no heap allocations).
If no seed is provided, a randomly generated one is created (using entropy from the system). See theseed!
function for reseeding an already existingXoshiro
object.
Passing a negative integer seed requires at least Julia 1.11.
Examples
julia> using Randomjulia> rng = Xoshiro(1234);julia> x1 = rand(rng, 2)2-element Vector{Float64}: 0.32597672886359486 0.5490511363155669julia> rng = Xoshiro(1234);julia> x2 = rand(rng, 2)2-element Vector{Float64}: 0.32597672886359486 0.5490511363155669julia> x1 == x2true
Random.MersenneTwister
—TypeMersenneTwister(seed)MersenneTwister()
Create aMersenneTwister
RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers. Theseed
may be an integer, a string, or a vector ofUInt32
integers. If no seed is provided, a randomly generated one is created (using entropy from the system). See theseed!
function for reseeding an already existingMersenneTwister
object.
Passing a negative integer seed requires at least Julia 1.11.
Examples
julia> rng = MersenneTwister(123);julia> x1 = rand(rng, 2)2-element Vector{Float64}: 0.37453777969575874 0.8735343642013971julia> x2 = rand(MersenneTwister(123), 2)2-element Vector{Float64}: 0.37453777969575874 0.8735343642013971julia> x1 == x2true
Random.RandomDevice
—TypeRandomDevice()
Create aRandomDevice
RNG object. Two such objects will always generate different streams of random numbers. The entropy is obtained from the operating system.
Random
APIThere are two mostly orthogonal ways to extendRandom
functionalities:
The API for 1) is quite functional, but is relatively recent so it may still have to evolve in subsequent releases of theRandom
module. For example, it's typically sufficient to implement onerand
method in order to have all other usual methods work automatically.
The API for 2) is still rudimentary, and may require more work than strictly necessary from the implementor, in order to support usual types of generated values.
Generating random values for some distributions may involve various trade-offs.Pre-computed values, such as analias table for discrete distributions, or“squeezing” functions for univariate distributions, can speed up sampling considerably. How much information should be pre-computed can depend on the number of values we plan to draw from a distribution. Also, some random number generators can have certain properties that various algorithms may want to exploit.
TheRandom
module defines a customizable framework for obtaining random values that can address these issues. Each invocation ofrand
generates asampler which can be customized with the above trade-offs in mind, by adding methods toSampler
, which in turn can dispatch on the random number generator, the object that characterizes the distribution, and a suggestion for the number of repetitions. Currently, for the latter,Val{1}
(for a single sample) andVal{Inf}
(for an arbitrary number) are used, withRandom.Repetition
an alias for both.
The object returned bySampler
is then used to generate the random values. When implementing the random generation interface for a valueX
that can be sampled from, the implementor should define the method
rand(rng, sampler)
for the particularsampler
returned bySampler(rng, X, repetition)
.
Samplers can be arbitrary values that implementrand(rng, sampler)
, but for most applications the following predefined samplers may be sufficient:
SamplerType{T}()
can be used for implementing samplers that draw from typeT
(e.g.rand(Int)
). This is the default returned bySampler
fortypes.
SamplerTrivial(self)
is a simple wrapper forself
, which can be accessed with[]
. This is the recommended sampler when no pre-computed information is needed (e.g.rand(1:3)
), and is the default returned bySampler
forvalues.
SamplerSimple(self, data)
also contains the additionaldata
field, which can be used to store arbitrary pre-computed values, which should be computed in acustom method ofSampler
.
We provide examples for each of these. We assume here that the choice of algorithm is independent of the RNG, so we useAbstractRNG
in our signatures.
Random.Sampler
—TypeSampler(rng, x, repetition = Val(Inf))
Return a sampler object that can be used to generate random values fromrng
forx
.
Whensp = Sampler(rng, x, repetition)
,rand(rng, sp)
will be used to draw random values, and should be defined accordingly.
repetition
can beVal(1)
orVal(Inf)
, and should be used as a suggestion for deciding the amount of precomputation, if applicable.
Random.SamplerType
andRandom.SamplerTrivial
are default fallbacks fortypes andvalues, respectively.Random.SamplerSimple
can be used to store pre-computed values without defining extra types for only this purpose.
Random.SamplerType
—TypeSamplerType{T}()
A sampler for types, containing no other information. The default fallback forSampler
when called with types.
Random.SamplerTrivial
—TypeSamplerTrivial(x)
Create a sampler that just wraps the given valuex
. This is the default fall-back for values. Theeltype
of this sampler is equal toeltype(x)
.
The recommended use case is sampling from values without precomputed data.
Random.SamplerSimple
—TypeSamplerSimple(x, data)
Create a sampler that wraps the given valuex
and thedata
. Theeltype
of this sampler is equal toeltype(x)
.
The recommended use case is sampling from values with precomputed data.
Decoupling pre-computation from actually generating the values is part of the API, and is also available to the user. As an example, assume thatrand(rng, 1:20)
has to be called repeatedly in a loop: the way to take advantage of this decoupling is as follows:
rng = Xoshiro()sp = Random.Sampler(rng, 1:20) # or Random.Sampler(Xoshiro, 1:20)for x in X n = rand(rng, sp) # similar to n = rand(rng, 1:20) # use nend
This is the mechanism that is also used in the standard library, e.g. by the default implementation of random array generation (like inrand(1:20, 10)
).
Given a typeT
, it's currently assumed that ifrand(T)
is defined, an object of typeT
will be produced.SamplerType
is thedefault sampler for types. In order to define random generation of values of typeT
, therand(rng::AbstractRNG, ::Random.SamplerType{T})
method should be defined, and should return values whatrand(rng, T)
is expected to return.
Let's take the following example: we implement aDie
type, with a variable numbern
of sides, numbered from1
ton
. We wantrand(Die)
to produce aDie
with a random number of up to 20 sides (and at least 4):
struct Die nsides::Int # number of sidesendRandom.rand(rng::AbstractRNG, ::Random.SamplerType{Die}) = Die(rand(rng, 4:20))# output
Scalar and array methods forDie
now work as expected:
julia> rand(Die)Die(5)julia> rand(Xoshiro(0), Die)Die(10)julia> rand(Die, 3)3-element Vector{Die}: Die(9) Die(15) Die(14)julia> a = Vector{Die}(undef, 3); rand!(a)3-element Vector{Die}: Die(19) Die(7) Die(17)
Here we define a sampler for a collection. If no pre-computed data is required, it can be implemented with aSamplerTrivial
sampler, which is in fact thedefault fallback for values.
In order to define random generation out of objects of typeS
, the following method should be defined:rand(rng::AbstractRNG, sp::Random.SamplerTrivial{S})
. Here,sp
simply wraps an object of typeS
, which can be accessed viasp[]
. Continuing theDie
example, we want now to definerand(d::Die)
to produce anInt
corresponding to one ofd
's sides:
julia> Random.rand(rng::AbstractRNG, d::Random.SamplerTrivial{Die}) = rand(rng, 1:d[].nsides);julia> rand(Die(4))1julia> rand(Die(4), 3)3-element Vector{Any}: 2 3 3
Given a collection typeS
, it's currently assumed that ifrand(::S)
is defined, an object of typeeltype(S)
will be produced. In the last example, aVector{Any}
is produced; the reason is thateltype(Die) == Any
. The remedy is to defineBase.eltype(::Type{Die}) = Int
.
AbstractFloat
typeAbstractFloat
types are special-cased, because by default random values are not produced in the whole type domain, but rather in[0,1)
. The following method should be implemented forT <: AbstractFloat
:Random.rand(::AbstractRNG, ::Random.SamplerTrivial{Random.CloseOpen01{T}})
Consider a discrete distribution, where numbers1:n
are drawn with given probabilities that sum to one. When many values are needed from this distribution, the fastest method is using analias table. We don't provide the algorithm for building such a table here, but suppose it is available inmake_alias_table(probabilities)
instead, anddraw_number(rng, alias_table)
can be used to draw a random number from it.
Suppose that the distribution is described by
struct DiscreteDistribution{V <: AbstractVector} probabilities::Vend
and that wealways want to build an alias table, regardless of the number of values needed (we learn how to customize this below). The methods
Random.eltype(::Type{<:DiscreteDistribution}) = Intfunction Random.Sampler(::Type{<:AbstractRNG}, distribution::DiscreteDistribution, ::Repetition) SamplerSimple(distribution, make_alias_table(distribution.probabilities))end
should be defined to return a sampler with pre-computed data, then
function rand(rng::AbstractRNG, sp::SamplerSimple{<:DiscreteDistribution}) draw_number(rng, sp.data)end
will be used to draw the values.
TheSamplerSimple
type is sufficient for most use cases with precomputed data. However, in order to demonstrate how to use custom sampler types, here we implement something similar toSamplerSimple
.
Going back to ourDie
example:rand(::Die)
uses random generation from a range, so there is an opportunity for this optimization. We call our custom samplerSamplerDie
.
import Random: Sampler, randstruct SamplerDie <: Sampler{Int} # generates values of type Int die::Die sp::Sampler{Int} # this is an abstract type, so this could be improvedendSampler(RNG::Type{<:AbstractRNG}, die::Die, r::Random.Repetition) = SamplerDie(die, Sampler(RNG, 1:die.nsides, r))# the `r` parameter will be explained later onrand(rng::AbstractRNG, sp::SamplerDie) = rand(rng, sp.sp)
It's now possible to get a sampler withsp = Sampler(rng, die)
, and usesp
instead ofdie
in anyrand
call involvingrng
. In the simplistic example above,die
doesn't need to be stored inSamplerDie
but this is often the case in practice.
Of course, this pattern is so frequent that the helper type used above, namelyRandom.SamplerSimple
, is available, saving us the definition ofSamplerDie
: we could have implemented our decoupling with:
Sampler(RNG::Type{<:AbstractRNG}, die::Die, r::Random.Repetition) = SamplerSimple(die, Sampler(RNG, 1:die.nsides, r))rand(rng::AbstractRNG, sp::SamplerSimple{Die}) = rand(rng, sp.data)
Here,sp.data
refers to the second parameter in the call to theSamplerSimple
constructor (in this case equal toSampler(rng, 1:die.nsides, r)
), while theDie
object can be accessed viasp[]
.
LikeSamplerDie
, any custom sampler must be a subtype ofSampler{T}
whereT
is the type of the generated values. Note thatSamplerSimple(x, data) isa Sampler{eltype(x)}
, so this constrains what the first argument toSamplerSimple
can be (it's recommended to useSamplerSimple
like in theDie
example, wherex
is simply forwarded while defining aSampler
method). Similarly,SamplerTrivial(x) isa Sampler{eltype(x)}
.
Another helper type is currently available for other cases,Random.SamplerTag
, but is considered as internal API, and can break at any time without proper deprecations.
In some cases, whether one wants to generate only a handful of values or a large number of values will have an impact on the choice of algorithm. This is handled with the third parameter of theSampler
constructor. Let's assume we defined two helper types forDie
, saySamplerDie1
which should be used to generate only few random values, andSamplerDieMany
for many values. We can use those types as follows:
Sampler(RNG::Type{<:AbstractRNG}, die::Die, ::Val{1}) = SamplerDie1(...)Sampler(RNG::Type{<:AbstractRNG}, die::Die, ::Val{Inf}) = SamplerDieMany(...)
Of course,rand
must also be defined on those types (i.e.rand(::AbstractRNG, ::SamplerDie1)
andrand(::AbstractRNG, ::SamplerDieMany)
). Note that, as usual,SamplerTrivial
andSamplerSimple
can be used if custom types are not necessary.
Note:Sampler(rng, x)
is simply a shorthand forSampler(rng, x, Val(Inf))
, andRandom.Repetition
is an alias forUnion{Val{1}, Val{Inf}}
.
The API is not clearly defined yet, but as a rule of thumb:
rand
method producing "basic" types (isbitstype
integer and floating types inBase
) should be defined for this specific RNG, if they are needed;rand
methods accepting anAbstractRNG
should work out of the box, (provided the methods from 1) what are relied on are implemented), but can of course be specialized for this RNG if there is room for optimization;copy
for pseudo-RNGs should return an independent copy that generates the exact same random sequence as the original from that point when called in the same way. When this is not feasible (e.g. hardware-based RNGs),copy
must not be implemented.Concerning 1), arand
method may happen to work automatically, but it's not officially supported and may break without warnings in a subsequent release.
To define a newrand
method for an hypotheticalMyRNG
generator, and a value specifications
(e.g.s == Int
, ors == 1:10
) of typeS==typeof(s)
orS==Type{s}
ifs
is a type, the same two methods as we saw before must be defined:
Sampler(::Type{MyRNG}, ::S, ::Repetition)
, which returns an object of type saySamplerS
rand(rng::MyRNG, sp::SamplerS)
It can happen thatSampler(rng::AbstractRNG, ::S, ::Repetition)
is already defined in theRandom
module. It would then be possible to skip step 1) in practice (if one wants to specialize generation for this particular RNG type), but the correspondingSamplerS
type is considered as internal detail, and may be changed without warning.
In some cases, for a given RNG type, generating an array of random values can be more efficient with a specialized method than by merely using the decoupling technique explained before. This is for example the case forMersenneTwister
, which natively writes random values in an array.
To implement this specialization forMyRNG
and for a specifications
, producing elements of typeS
, the following method can be defined:rand!(rng::MyRNG, a::AbstractArray{S}, ::SamplerS)
, whereSamplerS
is the type of the sampler returned bySampler(MyRNG, s, Val(Inf))
. Instead ofAbstractArray
, it's possible to implement the functionality only for a subtype, e.g.Array{S}
. The non-mutating array method ofrand
will automatically call this specialization internally.
By using an RNG parameter initialized with a given seed, you can reproduce the same pseudorandom number sequence when running your program multiple times. However, a minor release of Julia (e.g. 1.3 to 1.4)may change the sequence of pseudorandom numbers generated from a specific seed, in particular ifMersenneTwister
is used. (Even if the sequence produced by a low-level function likerand
does not change, the output of higher-level functions likerandsubseq
may change due to algorithm updates.) Rationale: guaranteeing that pseudorandom streams never change prohibits many algorithmic improvements.
If you need to guarantee exact reproducibility of random data, it is advisable to simplysave the data (e.g. as a supplementary attachment in a scientific publication). (You can also, of course, specify a particular Julia version and package manifest, especially if you require bit reproducibility.)
Software tests that rely onspecific "random" data should also generally either save the data, embed it into the test code, or use third-party packages likeStableRNGs.jl. On the other hand, tests that should pass formost random data (e.g. testingA \ (A*x) ≈ x
for a random matrixA = randn(n,n)
) can use an RNG with a fixed seed to ensure that simply running the test many times does not encounter a failure due to very improbable data (e.g. an extremely ill-conditioned matrix).
The statisticaldistribution from which random samples are drawnis guaranteed to be the same across any minor Julia releases.
Settings
This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.