• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #38162

06 Aug 2025 08:25PM UTC coverage: 25.688% (-43.6%) from 69.336%
#38162

push

local

web-flow
fix runtime cglobal builtin function implementation (#59210)

This had failed to be updated for the LazyLibrary changes to codegen.

12976 of 50513 relevant lines covered (25.69%)

676965.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

27.14
/stdlib/Random/src/Random.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
"""
4
    Random
5

6
Support for generating random numbers. Provides [`rand`](@ref), [`randn`](@ref),
7
[`AbstractRNG`](@ref), [`Xoshiro`](@ref), [`MersenneTwister`](@ref), and [`RandomDevice`](@ref).
8
"""
9
module Random
10

11
include("DSFMT.jl")
12

13
using .DSFMT
14
using Base.GMP.MPZ
15
using Base.GMP: Limb
16
using SHA: SHA, SHA2_256_CTX, SHA2_512_CTX, SHA_CTX
17

18
using Base: BitInteger, BitInteger_types, BitUnsigned, require_one_based_indexing,
19
    _throw_argerror
20

21
import Base: copymutable, copy, copy!, ==, hash, convert,
22
             rand, randn, show
23

24
export rand!, randn!,
25
       randexp, randexp!,
26
       bitrand,
27
       randstring,
28
       randsubseq, randsubseq!,
29
       shuffle, shuffle!,
30
       randperm, randperm!,
31
       randcycle, randcycle!,
32
       AbstractRNG, MersenneTwister, RandomDevice, TaskLocalRNG, Xoshiro
33

34
public seed!, default_rng, Sampler, SamplerType, SamplerTrivial, SamplerSimple
35

36
## general definitions
37

38
"""
39
    AbstractRNG
40

41
Supertype for random number generators such as [`MersenneTwister`](@ref) and [`RandomDevice`](@ref).
42
"""
43
abstract type AbstractRNG end
44

45
Base.broadcastable(x::AbstractRNG) = Ref(x)
×
46

47
gentype(::Type{X}) where {X} = eltype(X)
×
48
gentype(x) = gentype(typeof(x))
×
49

50

51
### integers
52

53
# we define types which encode the generation of a specific number of bits
54
# the "raw" version means that the unused bits are not zeroed
55

56
abstract type UniformBits{T<:BitInteger} end
57

58
struct UInt10{T}    <: UniformBits{T} end
59
struct UInt10Raw{T} <: UniformBits{T} end
60

61
struct UInt23{T}    <: UniformBits{T} end
62
struct UInt23Raw{T} <: UniformBits{T} end
63

64
struct UInt52{T}    <: UniformBits{T} end
65
struct UInt52Raw{T} <: UniformBits{T} end
66

67
struct UInt104{T}    <: UniformBits{T} end
68
struct UInt104Raw{T} <: UniformBits{T} end
69

70
struct UInt2x52{T}    <: UniformBits{T} end
71
struct UInt2x52Raw{T} <: UniformBits{T} end
72

73
uint_sup(::Type{<:Union{UInt10,UInt10Raw}}) = UInt16
×
74
uint_sup(::Type{<:Union{UInt23,UInt23Raw}}) = UInt32
×
75
uint_sup(::Type{<:Union{UInt52,UInt52Raw}}) = UInt64
×
76
uint_sup(::Type{<:Union{UInt104,UInt104Raw}}) = UInt128
×
77
uint_sup(::Type{<:Union{UInt2x52,UInt2x52Raw}}) = UInt128
×
78

79
for UI = (:UInt10, :UInt10Raw, :UInt23, :UInt23Raw, :UInt52, :UInt52Raw,
80
          :UInt104, :UInt104Raw, :UInt2x52, :UInt2x52Raw)
81
    @eval begin
82
        $UI(::Type{T}=uint_sup($UI)) where {T} = $UI{T}()
×
83
        # useful for defining rand generically:
84
        uint_default(::$UI) = $UI{uint_sup($UI)}()
×
85
    end
86
end
87

88
gentype(::Type{<:UniformBits{T}}) where {T} = T
×
89

90
### floats
91

92
abstract type FloatInterval{T<:AbstractFloat} end
93

94
struct CloseOpen01{T<:AbstractFloat} <: FloatInterval{T} end # interval [0,1)
95
struct CloseOpen12{T<:AbstractFloat} <: FloatInterval{T} end # interval [1,2)
96

97
const FloatInterval_64 = FloatInterval{Float64}
98
const CloseOpen01_64   = CloseOpen01{Float64}
99
const CloseOpen12_64   = CloseOpen12{Float64}
100

101
CloseOpen01(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen01{T}()
×
102
CloseOpen12(::Type{T}=Float64) where {T<:AbstractFloat} = CloseOpen12{T}()
×
103

104
gentype(::Type{<:FloatInterval{T}}) where {T<:AbstractFloat} = T
×
105

106
const BitFloatType = Union{Type{Float16},Type{Float32},Type{Float64}}
107

108
### Sampler
109

110
abstract type Sampler{E} end
111

112
gentype(::Type{<:Sampler{E}}) where {E} = E
×
113

114
# temporarily for BaseBenchmarks
115
RangeGenerator(x) = Sampler(default_rng(), x)
×
116

117
# In some cases, when only 1 random value is to be generated,
118
# the optimal sampler can be different than if multiple values
119
# have to be generated. Hence a `Repetition` parameter is used
120
# to choose the best one depending on the need.
121
const Repetition = Union{Val{1},Val{Inf}}
122

123
# these default fall-back for all RNGs would be nice,
124
# but generate difficult-to-solve ambiguities
125
# Sampler(::AbstractRNG, X, ::Val{Inf}) = Sampler(X)
126
# Sampler(::AbstractRNG, ::Type{X}, ::Val{Inf}) where {X} = Sampler(X)
127

128
"""
129
    Sampler(rng, x, repetition = Val(Inf))
130

131
Return a sampler object that can be used to generate random values from `rng` for `x`.
132

133
When `sp = Sampler(rng, x, repetition)`, `rand(rng, sp)` will be used to draw random values,
134
and should be defined accordingly.
135

136
`repetition` can be `Val(1)` or `Val(Inf)`, and should be used as a suggestion for deciding
137
the amount of precomputation, if applicable.
138

139
[`Random.SamplerType`](@ref) and [`Random.SamplerTrivial`](@ref) are default fallbacks for
140
*types* and *values*, respectively. [`Random.SamplerSimple`](@ref) can be used to store
141
pre-computed values without defining extra types for only this purpose.
142
"""
143
Sampler(rng::AbstractRNG, x, r::Repetition=Val(Inf)) = Sampler(typeof(rng), x, r)
172✔
144
Sampler(rng::AbstractRNG, ::Type{X}, r::Repetition=Val(Inf)) where {X} =
1✔
145
    Sampler(typeof(rng), X, r)
146

147
# this method is necessary to prevent rand(rng::AbstractRNG, X) from
148
# recursively constructing nested Sampler types.
149
Sampler(T::Type{<:AbstractRNG}, sp::Sampler, r::Repetition) =
×
150
    throw(MethodError(Sampler, (T, sp, r)))
151

152
# default shortcut for the general case
153
Sampler(::Type{RNG}, X) where {RNG<:AbstractRNG} = Sampler(RNG, X, Val(Inf))
×
154
Sampler(::Type{RNG}, ::Type{X}) where {RNG<:AbstractRNG,X} = Sampler(RNG, X, Val(Inf))
×
155

156
#### pre-defined useful Sampler types
157

158
"""
159
    SamplerType{T}()
160

161
A sampler for types, containing no other information. The default fallback for `Sampler`
162
when called with types.
163
"""
164
struct SamplerType{T} <: Sampler{T} end
165

166
Sampler(::Type{<:AbstractRNG}, ::Type{T}, ::Repetition) where {T} = SamplerType{T}()
1✔
167

168
Base.getindex(::SamplerType{T}) where {T} = T
×
169

170
# SamplerUnion(X, Y, ...}) == Union{SamplerType{X}, SamplerType{Y}, ...}
171
SamplerUnion(U...) = Union{Any[SamplerType{T} for T in U]...}
×
172
const SamplerBoolBitInteger = SamplerUnion(Bool, BitInteger_types...)
173

174

175
struct SamplerTrivial{T,E} <: Sampler{E}
176
    self::T
177
end
178

179
"""
180
    SamplerTrivial(x)
181

182
Create a sampler that just wraps the given value `x`. This is the default fall-back for
183
values.
184
The `eltype` of this sampler is equal to `eltype(x)`.
185

186
The recommended use case is sampling from values without precomputed data.
187
"""
188
SamplerTrivial(x::T) where {T} = SamplerTrivial{T,gentype(T)}(x)
×
189

190
Sampler(::Type{<:AbstractRNG}, x, ::Repetition) = SamplerTrivial(x)
×
191

192
Base.getindex(sp::SamplerTrivial) = sp.self
×
193

194
# simple sampler carrying data (which can be anything)
195
struct SamplerSimple{T,S,E} <: Sampler{E}
196
    self::T
85✔
197
    data::S
198
end
199

200
"""
201
    SamplerSimple(x, data)
202

203
Create a sampler that wraps the given value `x` and the `data`.
204
The `eltype` of this sampler is equal to `eltype(x)`.
205

206
The recommended use case is sampling from values with precomputed data.
207
"""
208
SamplerSimple(x::T, data::S) where {T,S} = SamplerSimple{T,S,gentype(T)}(x, data)
85✔
209

210
Base.getindex(sp::SamplerSimple) = sp.self
16✔
211

212
# simple sampler carrying a (type) tag T and data
213
struct SamplerTag{T,S,E} <: Sampler{E}
214
    data::S
215
    SamplerTag{T}(s::S) where {T,S} = new{T,S,gentype(T)}(s)
×
216
end
217

218

219
#### helper samplers
220

221
# TODO: make constraining constructors to enforce that those
222
# types are <: Sampler{T}
223

224
##### Adapter to generate a random value in [0, n]
225

226
struct LessThan{T<:Integer,S} <: Sampler{T}
227
    sup::T
228
    s::S    # the scalar specification/sampler to feed to rand
229
end
230

231
function rand(rng::AbstractRNG, sp::LessThan)
×
232
    while true
×
233
        x = rand(rng, sp.s)
×
234
        x <= sp.sup && return x
×
235
    end
×
236
end
237

238
struct Masked{T<:Integer,S} <: Sampler{T}
239
    mask::T
240
    s::S
241
end
242

243
rand(rng::AbstractRNG, sp::Masked) = rand(rng, sp.s) & sp.mask
×
244

245
##### Uniform
246

247
struct UniformT{T} <: Sampler{T} end
248

249
uniform(::Type{T}) where {T} = UniformT{T}()
×
250

251
rand(rng::AbstractRNG, ::UniformT{T}) where {T} = rand(rng, T)
×
252

253

254
### machinery for generation with Sampler
255

256
# This describes how to generate random scalars or arrays, by generating a Sampler
257
# and calling rand on it (which should be defined in "generation.jl").
258
# NOTE: this section could be moved into a separate file when more containers are supported.
259

260
#### scalars
261

262
rand(rng::AbstractRNG, X)                                           = rand(rng, Sampler(rng, X, Val(1)))
4✔
263
# this is needed to disambiguate
264
rand(rng::AbstractRNG, X::Dims)                                     = rand(rng, Sampler(rng, X, Val(1)))
×
265
rand(rng::AbstractRNG=default_rng(), ::Type{X}=Float64) where {X}   = rand(rng, Sampler(rng, X, Val(1)))::X
55✔
266

267
rand(X)                   = rand(default_rng(), X)
4✔
268
rand(::Type{X}) where {X} = rand(default_rng(), X)
123✔
269

270
#### arrays
271

272
rand!(A::AbstractArray{T}, X) where {T}             = rand!(default_rng(), A, X)
×
273
rand!(A::AbstractArray{T}, ::Type{X}=T) where {T,X} = rand!(default_rng(), A, X)
×
274

275
rand!(rng::AbstractRNG, A::AbstractArray{T}, X) where {T}             = rand!(rng, A, Sampler(rng, X))
85✔
276
rand!(rng::AbstractRNG, A::AbstractArray{T}, ::Type{X}=T) where {T,X} = rand!(rng, A, Sampler(rng, X))
×
277

278
function rand!(rng::AbstractRNG, A::AbstractArray{T}, sp::Sampler) where T
1✔
279
    for i in eachindex(A)
1✔
280
        @inbounds A[i] = rand(rng, sp)
16✔
281
    end
31✔
282
    A
1✔
283
end
284

285
rand(r::AbstractRNG, dims::Integer...) = rand(r, Float64, Dims(dims))
×
286
rand(                dims::Integer...) = rand(Float64, Dims(dims))
×
287

288
rand(r::AbstractRNG, X, dims::Dims)  = rand!(r, Array{gentype(X)}(undef, dims), X)
×
289
rand(                X, dims::Dims)  = rand(default_rng(), X, dims)
×
290

291
rand(r::AbstractRNG, X, d::Integer, dims::Integer...) = rand(r, X, Dims((d, dims...)))
×
292
rand(                X, d::Integer, dims::Integer...) = rand(X, Dims((d, dims...)))
×
293
# note: the above methods would trigger an ambiguity warning if d was not separated out:
294
# rand(r, ()) would match both this method and rand(r, dims::Dims)
295
# moreover, a call like rand(r, NotImplementedType()) would be an infinite loop
296

297
rand(r::AbstractRNG, ::Type{X}, dims::Dims) where {X} = rand!(r, Array{X}(undef, dims), X)
×
298
rand(                ::Type{X}, dims::Dims) where {X} = rand(default_rng(), X, dims)
×
299

300
rand(r::AbstractRNG, ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(r, X, Dims((d, dims...)))
×
301
rand(                ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(X, Dims((d, dims...)))
×
302

303

304
### UnsafeView
305
# internal array-like type to circumvent the lack of flexibility with reinterpret
306

307
struct UnsafeView{T} <: DenseArray{T,1}
308
    ptr::Ptr{T}
85✔
309
    len::Int
310
end
311

312
Base.length(a::UnsafeView) = a.len
×
313
Base.getindex(a::UnsafeView, i::Int) = unsafe_load(a.ptr, i)
×
314
Base.setindex!(a::UnsafeView, x, i::Int) = unsafe_store!(a.ptr, x, i)
16✔
315
Base.pointer(a::UnsafeView) = a.ptr
×
316
Base.size(a::UnsafeView) = (a.len,)
1✔
317
Base.elsize(::Type{UnsafeView{T}}) where {T} = sizeof(T)
×
318

319

320
## rand & rand! docstrings
321

322
"""
323
    rand([rng=default_rng()], [S], [dims...])
324

325
Pick a random element or array of random elements from the set of values specified by `S`;
326
`S` can be
327

328
* an indexable collection (for example `1:9` or `('x', "y", :z)`)
329

330
* an `AbstractDict` or `AbstractSet` object
331

332
* a string (considered as a collection of characters), or
333

334
* a type from the list below, corresponding to the specified set of values
335

336
  + concrete integer types sample from `typemin(S):typemax(S)` (excepting [`BigInt`](@ref) which is not supported)
337

338
  + concrete floating point types sample from `[0, 1)`
339

340
  + concrete complex types `Complex{T}` if `T` is a sampleable type take their real and imaginary components
341
    independently from the set of values corresponding to `T`, but are not supported if `T` is not sampleable.
342

343
  + all `<:AbstractChar` types sample from the set of valid Unicode scalars
344

345
  + a user-defined type and set of values; for implementation guidance please see [Hooking into the `Random` API](@ref rand-api-hook)
346

347
  + a tuple type of known size and where each parameter of `S` is itself a sampleable type; return a value of type `S`.
348
    Note that tuple types such as `Tuple{Vararg{T}}` (unknown size) and `Tuple{1:2}` (parameterized with a value) are not supported
349

350
  + a `Pair` type, e.g. `Pair{X, Y}` such that `rand` is defined for `X` and `Y`,
351
    in which case random pairs are produced.
352

353

354
`S` defaults to [`Float64`](@ref).
355
When only one argument is passed besides the optional `rng` and is a `Tuple`, it is interpreted
356
as a collection of values (`S`) and not as `dims`.
357

358

359
See also [`randn`](@ref) for normally distributed numbers, and [`rand!`](@ref) and [`randn!`](@ref) for the in-place equivalents.
360

361
!!! compat "Julia 1.1"
362
    Support for `S` as a tuple requires at least Julia 1.1.
363

364
!!! compat "Julia 1.11"
365
    Support for `S` as a `Tuple` type requires at least Julia 1.11.
366

367
# Examples
368
```julia-repl
369
julia> rand(Int, 2)
370
2-element Vector{Int64}:
371
 1339893410598768192
372
 1575814717733606317
373

374
julia> using Random
375

376
julia> rand(Xoshiro(0), Dict(1=>2, 3=>4))
377
3 => 4
378

379
julia> rand((2, 3))
380
3
381

382
julia> rand(Float64, (2, 3))
383
2×3 Matrix{Float64}:
384
 0.999717  0.0143835  0.540787
385
 0.696556  0.783855   0.938235
386
```
387

388
!!! note
389
    The complexity of `rand(rng, s::Union{AbstractDict,AbstractSet})`
390
    is linear in the length of `s`, unless an optimized method with
391
    constant complexity is available, which is the case for `Dict`,
392
    `Set` and dense `BitSet`s. For more than a few calls, use `rand(rng,
393
    collect(s))` instead, or either `rand(rng, Dict(s))` or `rand(rng,
394
    Set(s))` as appropriate.
395
"""
396
rand
397

398
"""
399
    rand!([rng=default_rng()], A, [S=eltype(A)])
400

401
Populate the array `A` with random values. If `S` is specified
402
(`S` can be a type or a collection, cf. [`rand`](@ref) for details),
403
the values are picked randomly from `S`.
404
This is equivalent to `copyto!(A, rand(rng, S, size(A)))`
405
but without allocating a new array.
406

407
# Examples
408
```jldoctest
409
julia> rand!(Xoshiro(123), zeros(5))
410
5-element Vector{Float64}:
411
 0.521213795535383
412
 0.5868067574533484
413
 0.8908786980927811
414
 0.19090669902576285
415
 0.5256623915420473
416
```
417
"""
418
rand!
419

420

421
include("Xoshiro.jl")
422
include("RNGs.jl")
423
include("MersenneTwister.jl")
424
include("generation.jl")
425
include("normal.jl")
426
include("misc.jl")
427
include("XoshiroSimd.jl")
428

429
end # module
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc