RandomExtensions
Most of the "documentation" is still in the README. Here is the updated docstring for rand
:
Base.rand
— Functionrand([rng=default_rng()], [S], [C...]) # RandomExtensions
Pick a random element or collection 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; - a
Distribution
object, e.g.Normal()
for a normal distribution (likerandn()
), orCloseOpen(10.0, 20.0)
for uniformFloat64
numbers in the range $[10.0, 20.0)$; - a
make
object, which can be e.g.make(Pair, S1, S2)
ormake(Complex, S1, S2)
, whereS1
andS2
are one of the specifications above;Pair
orComplex
can optionally be given as concrete types, e.g.make(ComplexF64, 1:3, Int)
to generateComplexF64
instead ofComplex{Int}
.
S
usually defaults to Float64
.
If C...
is not specified, rand
produces a scalar. Otherwise, C
can be:
- a set of integers, or a tuple of
Int
, which specify the dimensions of anArray
to generate; (Array, dims...)
: same as above, but withArray
specified explicitely;(p::AbstractFloat, m::Integer, [n::Integer])
, which produces a sparse array of dimensions(m, n)
, in which the probability of any element being nonzero is independently given byp
;(String, [n=8])
, which produces a randomString
of lengthn
; the generated string consists ofChar
taken from a predefined set likerandstring
, and can be specified with theS
parameter;(Dict, n)
, which produces aDict
of lengthn
; ifDict
is given without type parameters, thenS
must be specified;(Set, n)
or(BitSet, n)
, which produces a set of lengthn
;(BitArray, dims...)
, which produces aBitArray
with the specified dimensions.
For Array
, Dict
and Set
, a less abstract type can be specified, e.g. Set{Float64}
, to force the type of the result regardless of the S
parameter. In particular, in the absence of S
, the type parameter(s) of the container play the role of S
; for example, rand(Dict{Int,Float64}, n)
is equivalent to rand(make(Pair, Int, Float64), Dict, n)
.
Examples
julia> rand(Int, 2)
2-element Array{Int64,1}:
1339893410598768192
1575814717733606317
julia> rand(MersenneTwister(0), Dict(1=>2, 3=>4))
1=>2
julia> rand("abc", String, 12)
"bccaacaabaac"
julia> rand(1:10, Set, 3)
Set([3, 8, 6])
julia> rand(1:10, Set{Float64}, 3)
Set([10.0, 5.0, 6.0])
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.