From f42b73d59b82fb955d41f192898666adb5c639c4 Mon Sep 17 00:00:00 2001 From: Rafael Fourquet Date: Fri, 1 Dec 2017 13:11:28 +0100 Subject: [PATCH] move Random to stdlib --- base/abstractarray.jl | 2 + base/deprecated.jl | 32 +++- base/docs/basedocs.jl | 2 + base/error.jl | 2 +- base/essentials.jl | 2 + base/event.jl | 2 + base/exports.jl | 23 --- base/file.jl | 2 +- base/multimedia.jl | 2 + base/number.jl | 2 + base/permuteddimsarray.jl | 2 + base/serialize.jl | 10 -- base/sparse/linalg.jl | 6 - base/sparse/sparse.jl | 4 +- base/sparse/sparsematrix.jl | 113 ------------- base/sparse/sparsevector.jl | 25 --- base/sysimg.jl | 20 ++- base/task.jl | 2 + doc/make.jl | 5 +- doc/src/stdlib/.gitignore | 1 + doc/src/stdlib/arrays.md | 2 - doc/src/stdlib/numbers.md | 35 ---- stdlib/Base64/test/runtests.jl | 2 +- stdlib/CRC32c/test/runtests.jl | 3 +- stdlib/DelimitedFiles/test/runtests.jl | 2 +- stdlib/Distributed/src/cluster.jl | 2 + stdlib/Distributed/test/distributed_exec.jl | 3 +- stdlib/Distributed/test/topology.jl | 2 + stdlib/IterativeEigenSolvers/test/runtests.jl | 2 +- stdlib/Mmap/test/runtests.jl | 2 +- stdlib/Random/docs/src/index.md | 36 ++++ {base/random => stdlib/Random/src}/RNGs.jl | 10 ++ .../random.jl => stdlib/Random/src/Random.jl | 24 ++- {base/random => stdlib/Random/src}/dSFMT.jl | 0 .../Random/src}/generation.jl | 0 {base/random => stdlib/Random/src}/misc.jl | 6 +- {base/random => stdlib/Random/src}/normal.jl | 0 stdlib/Random/src/sparse.jl | 155 ++++++++++++++++++ .../Random/test/runtests.jl | 50 +++--- stdlib/SharedArrays/src/SharedArrays.jl | 8 +- stdlib/SharedArrays/test/runtests.jl | 2 +- stdlib/SuiteSparse/test/runtests.jl | 2 +- stdlib/Test/src/Test.jl | 5 +- test/abstractarray.jl | 2 + test/arrayops.jl | 2 + test/asyncmap.jl | 2 + test/bigint.jl | 2 + test/bitarray.jl | 1 + test/bitset.jl | 2 + test/boundscheck_exec.jl | 2 +- test/broadcast.jl | 2 +- test/ccall.jl | 1 + test/channels.jl | 2 + test/choosetests.jl | 2 + test/codegen.jl | 2 + test/combinatorics.jl | 2 + test/compile.jl | 2 +- test/copy.jl | 2 + test/core.jl | 3 + test/dict.jl | 2 + test/env.jl | 2 + test/examples.jl | 2 + test/floatfuncs.jl | 2 +- test/hashing.jl | 2 + test/inference.jl | 2 + test/int.jl | 1 + test/intfuncs.jl | 2 + test/iobuffer.jl | 2 + test/iterators.jl | 1 + test/libgit2-online.jl | 2 + test/libgit2.jl | 2 + test/linalg/bidiag.jl | 2 +- test/linalg/blas.jl | 2 + test/linalg/bunchkaufman.jl | 2 +- test/linalg/cholesky.jl | 2 +- test/linalg/dense.jl | 2 +- test/linalg/diagonal.jl | 2 +- test/linalg/eigen.jl | 2 +- test/linalg/generic.jl | 4 +- test/linalg/givens.jl | 2 +- test/linalg/hessenberg.jl | 2 +- test/linalg/lapack.jl | 2 +- test/linalg/lq.jl | 2 +- test/linalg/matmul.jl | 2 +- test/linalg/pinv.jl | 2 +- test/linalg/qr.jl | 2 +- test/linalg/rowvector.jl | 2 + test/linalg/schur.jl | 2 +- test/linalg/special.jl | 2 +- test/linalg/svd.jl | 2 +- test/linalg/symmetric.jl | 2 +- test/linalg/triangular.jl | 2 +- test/linalg/tridiag.jl | 2 + test/linalg/uniformscaling.jl | 2 +- test/math.jl | 2 + test/misc.jl | 2 + test/nullable.jl | 2 + test/numbers.jl | 2 + test/offsetarray.jl | 1 + test/operators.jl | 2 + test/perf/perfutil.jl | 2 + test/perf/simd/sum_reduce.jl | 1 - test/pkg.jl | 1 + test/ranges.jl | 2 +- test/read.jl | 1 + test/reduce.jl | 2 + test/reducedim.jl | 2 + test/reflection.jl | 2 +- test/repl.jl | 1 + test/replcompletions.jl | 3 +- test/replutil.jl | 2 + test/serialize.jl | 2 +- test/socket.jl | 2 + test/sorting.jl | 1 + test/sparse/higherorderfns.jl | 2 + test/sparse/sparse.jl | 1 + test/sparse/sparsevector.jl | 1 + test/spawn.jl | 3 +- test/staged.jl | 2 + test/statistics.jl | 2 +- test/strings/basic.jl | 2 + test/subarray.jl | 2 +- test/syntax.jl | 2 + test/testdefs.jl | 4 +- test/version.jl | 2 + 125 files changed, 458 insertions(+), 313 deletions(-) create mode 100644 stdlib/Random/docs/src/index.md rename {base/random => stdlib/Random/src}/RNGs.jl (98%) rename base/random/random.jl => stdlib/Random/src/Random.jl (93%) rename {base/random => stdlib/Random/src}/dSFMT.jl (100%) rename {base/random => stdlib/Random/src}/generation.jl (100%) rename {base/random => stdlib/Random/src}/misc.jl (99%) rename {base/random => stdlib/Random/src}/normal.jl (100%) create mode 100644 stdlib/Random/src/sparse.jl rename test/random.jl => stdlib/Random/test/runtests.jl (95%) diff --git a/base/abstractarray.jl b/base/abstractarray.jl index 4c1ad65d92dd3..cf6ca6f0d1a84 100644 --- a/base/abstractarray.jl +++ b/base/abstractarray.jl @@ -359,6 +359,8 @@ See also [`checkindex`](@ref). # Examples ```jldoctest +julia> using Random + julia> A = rand(3, 3); julia> checkbounds(Bool, A, 2) diff --git a/base/deprecated.jl b/base/deprecated.jl index 860f839acce0a..27c85d4dff4d6 100644 --- a/base/deprecated.jl +++ b/base/deprecated.jl @@ -1130,12 +1130,6 @@ end import .LinAlg: cond @deprecate cond(F::LinAlg.LU, p::Integer) cond(convert(AbstractArray, F), p) -# PR #21359 -import .Random: srand -@deprecate srand(r::MersenneTwister, filename::AbstractString, n::Integer=4) srand(r, read!(filename, Vector{UInt32}(uninitialized, Int(n)))) -@deprecate srand(filename::AbstractString, n::Integer=4) srand(read!(filename, Vector{UInt32}(uninitialized, Int(n)))) -@deprecate MersenneTwister(filename::AbstractString) srand(MersenneTwister(0), read!(filename, Vector{UInt32}(uninitialized, Int(4)))) - # PR #21974 @deprecate versioninfo(verbose::Bool) versioninfo(verbose=verbose) @deprecate versioninfo(io::IO, verbose::Bool) versioninfo(io, verbose=verbose) @@ -2987,6 +2981,32 @@ end # issue #24822 @deprecate_binding Display AbstractDisplay +# PR #24874 +@deprecate_moved rand "Random" true true +@deprecate_moved rand! "Random" true true +@deprecate_moved srand "Random" true true +@deprecate_moved AbstractRNG "Random" true true +@deprecate_moved sprand "Random" true true +@deprecate_moved sprandn "Random" true true +@deprecate_moved randcycle "Random" true true +@deprecate_moved randcycle! "Random" true true +@deprecate_moved randperm "Random" true true +@deprecate_moved randperm! "Random" true true +@deprecate_moved shuffle "Random" true true +@deprecate_moved shuffle! "Random" true true +@deprecate_moved randsubseq "Random" true true +@deprecate_moved randsubseq! "Random" true true +@deprecate_moved randstring "Random" true true +@deprecate_moved MersenneTwister "Random" true true +@deprecate_moved RandomDevice "Random" true true +@deprecate_moved randn "Random" true true +@deprecate_moved randn! "Random" true true +@deprecate_moved randexp "Random" true true +@deprecate_moved randexp! "Random" true true +@deprecate_moved bitrand "Random" true true +@deprecate_moved randjump "Random" true true +@deprecate_moved GLOBAL_RNG "Random" true true + # 24595 @deprecate falses(A::AbstractArray) falses(size(A)) @deprecate trues(A::AbstractArray) trues(size(A)) diff --git a/base/docs/basedocs.jl b/base/docs/basedocs.jl index cfc1bd47da829..af2fa80ff12e2 100644 --- a/base/docs/basedocs.jl +++ b/base/docs/basedocs.jl @@ -988,6 +988,8 @@ callable with no arguments). The task exits when this function returns. # Examples ```jldoctest +julia> using Random + julia> a() = det(rand(1000, 1000)); julia> b = Task(a); diff --git a/base/error.jl b/base/error.jl index 9446b2c79b4d6..1dfac57c08576 100644 --- a/base/error.jl +++ b/base/error.jl @@ -172,7 +172,7 @@ start(ebo::ExponentialBackOff) = (ebo.n, min(ebo.first_delay, ebo.max_delay)) function next(ebo::ExponentialBackOff, state) next_n = state[1]-1 curr_delay = state[2] - next_delay = min(ebo.max_delay, state[2] * ebo.factor * (1.0 - ebo.jitter + (rand() * 2.0 * ebo.jitter))) + next_delay = min(ebo.max_delay, state[2] * ebo.factor * (1.0 - ebo.jitter + (Crand(Float64) * 2.0 * ebo.jitter))) (curr_delay, (next_n, next_delay)) end done(ebo::ExponentialBackOff, state) = state[1]<1 diff --git a/base/essentials.jl b/base/essentials.jl index cf7505bddbb59..8d09f78979860 100644 --- a/base/essentials.jl +++ b/base/essentials.jl @@ -574,6 +574,8 @@ if the index is out of bounds, or has an undefined reference. # Examples ```jldoctest +julia> using Random + julia> isassigned(rand(3, 3), 5) true diff --git a/base/event.jl b/base/event.jl index 2e791ab2cc0b1..6f821fb72814d 100644 --- a/base/event.jl +++ b/base/event.jl @@ -118,6 +118,8 @@ If a second argument `val` is provided, it will be passed to the task (via the r the woken task. ```jldoctest +julia> using Random + julia> a5() = det(rand(1000, 1000)); julia> b = Task(a5); diff --git a/base/exports.jl b/base/exports.jl index 3d2c355994b1d..413e81f3790d9 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -490,12 +490,6 @@ export prod!, prod, promote_shape, - randcycle, - randcycle!, - randperm, - randperm!, - randsubseq!, - randsubseq, range, reducedim, repmat, @@ -744,7 +738,6 @@ export print_shortest, print_with_color, println, - randstring, repeat, replace, repr, @@ -775,20 +768,6 @@ export @warn, @error, -# random numbers - AbstractRNG, - MersenneTwister, - RandomDevice, - rand!, - rand, - randn!, - randn, - randexp!, - randexp, - srand, - bitrand, - randjump, - # bigfloat & precision precision, rounding, @@ -1240,8 +1219,6 @@ export sparsevec, spdiagm, spones, - sprand, - sprandn, spzeros, rowvals, nzrange, diff --git a/base/file.jl b/base/file.jl index 7678cabf0d4ef..d3233946127b9 100644 --- a/base/file.jl +++ b/base/file.jl @@ -285,7 +285,7 @@ function mktemp(parent=tempdir()) end function mktempdir(parent=tempdir()) - seed::UInt32 = rand(UInt32) + seed::UInt32 = Crand(UInt32) while true if (seed & typemax(UInt16)) == 0 seed += 1 diff --git a/base/multimedia.jl b/base/multimedia.jl index e26a7f854bcda..dff455c165fc1 100644 --- a/base/multimedia.jl +++ b/base/multimedia.jl @@ -34,6 +34,8 @@ corresponding [`show`](@ref) method for `typeof(x)`.) # Examples ```jldoctest +julia> using Random + julia> mimewritable(MIME("text/plain"), rand(5)) true diff --git a/base/number.jl b/base/number.jl index 18f63c386f578..2aaa7d696a3a5 100644 --- a/base/number.jl +++ b/base/number.jl @@ -228,6 +228,8 @@ julia> zero(1) julia> zero(big"2.0") 0.0 +julia> using Random + julia> zero(rand(2,2)) 2×2 Array{Float64,2}: 0.0 0.0 diff --git a/base/permuteddimsarray.jl b/base/permuteddimsarray.jl index 20e5fba8579ae..44c873c3a471c 100644 --- a/base/permuteddimsarray.jl +++ b/base/permuteddimsarray.jl @@ -28,6 +28,8 @@ See also: [`permutedims`](@ref). # Examples ```jldoctest +julia> using Random + julia> A = rand(3,5,4); julia> B = PermutedDimsArray(A, (3,1,2)); diff --git a/base/serialize.jl b/base/serialize.jl index fe052f82175da..b7e2c09010fd7 100644 --- a/base/serialize.jl +++ b/base/serialize.jl @@ -1195,14 +1195,4 @@ function deserialize(s::AbstractSerializer, t::Type{Regex}) Regex(pattern, compile_options, match_options) end -if !Sys.iswindows() - function serialize(s::AbstractSerializer, rd::RandomDevice) - serialize_type(s, typeof(rd)) - serialize(s, rd.unlimited) - end - function deserialize(s::AbstractSerializer, t::Type{RandomDevice}) - unlimited = deserialize(s) - return RandomDevice(unlimited) - end -end end diff --git a/base/sparse/linalg.jl b/base/sparse/linalg.jl index c30c0e7fc6e50..8b0459563c38b 100644 --- a/base/sparse/linalg.jl +++ b/base/sparse/linalg.jl @@ -608,12 +608,6 @@ function normestinv(A::SparseMatrixCSC{T}, t::Integer = min(2,maximum(size(A)))) S = zeros(T <: Real ? Int : Ti, n, t) - function _rand_pm1!(v) - for i in eachindex(v) - v[i] = rand()<0.5 ? 1 : -1 - end - end - function _any_abs_eq(v,n::Int) for vv in v if abs(vv)==n diff --git a/base/sparse/sparse.jl b/base/sparse/sparse.jl index dcc9665c20fd6..05ba0cbe82edd 100644 --- a/base/sparse/sparse.jl +++ b/base/sparse/sparse.jl @@ -27,12 +27,12 @@ import Base: @get!, acos, acosd, acot, acotd, acsch, asech, asin, asind, asinh, vcat, hcat, hvcat, cat, imag, indmax, ishermitian, kron, length, log, log1p, max, min, maximum, minimum, norm, one, promote_eltype, real, reshape, rot180, rotl90, rotr90, round, scale!, setindex!, similar, size, transpose, tril, - triu, vec, permute!, map, map! + triu, vec, permute!, map, map!, _rand_pm1! export AbstractSparseArray, AbstractSparseMatrix, AbstractSparseVector, SparseMatrixCSC, SparseVector, blkdiag, droptol!, dropzeros!, dropzeros, issparse, nonzeros, nzrange, rowvals, sparse, sparsevec, spdiagm, spones, - sprand, sprandn, spzeros, nnz, permute + spzeros, nnz, permute include("abstractsparse.jl") include("sparsematrix.jl") diff --git a/base/sparse/sparsematrix.jl b/base/sparse/sparsematrix.jl index f0a80e8d9da62..0f268dcf73d6d 100644 --- a/base/sparse/sparsematrix.jl +++ b/base/sparse/sparsematrix.jl @@ -1318,119 +1318,6 @@ function findnz(S::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} return (I, J, V) end -import Base.Random.GLOBAL_RNG -function sprand_IJ(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) - ((m < 0) || (n < 0)) && throw(ArgumentError("invalid Array dimensions")) - 0 <= density <= 1 || throw(ArgumentError("$density not in [0,1]")) - N = n*m - - I, J = Vector{Int}(), Vector{Int}() # indices of nonzero elements - sizehint!(I, round(Int,N*density)) - sizehint!(J, round(Int,N*density)) - - # density of nonzero columns: - L = log1p(-density) - coldensity = -expm1(m*L) # = 1 - (1-density)^m - colsparsity = exp(m*L) # = 1 - coldensity - iL = 1/L - - rows = Vector{Int}() - for j in randsubseq(r, 1:n, coldensity) - # To get the right statistics, we *must* have a nonempty column j - # even if p*m << 1. To do this, we use an approach similar to - # the one in randsubseq to compute the expected first nonzero row k, - # except given that at least one is nonzero (via Bayes' rule); - # carefully rearranged to avoid excessive roundoff errors. - k = ceil(log(colsparsity + rand(r)*coldensity) * iL) - ik = k < 1 ? 1 : k > m ? m : Int(k) # roundoff-error/underflow paranoia - randsubseq!(r, rows, 1:m-ik, density) - push!(rows, m-ik+1) - append!(I, rows) - nrows = length(rows) - Jlen = length(J) - resize!(J, Jlen+nrows) - @inbounds for i = Jlen+1:length(J) - J[i] = j - end - end - I, J -end - -""" - sprand([rng],[type],m,[n],p::AbstractFloat,[rfn]) - -Create a random length `m` sparse vector or `m` by `n` sparse matrix, in -which the probability of any element being nonzero is independently given by -`p` (and hence the mean density of nonzeros is also exactly `p`). Nonzero -values are sampled from the distribution specified by `rfn` and have the type `type`. The uniform -distribution is used in case `rfn` is not specified. The optional `rng` -argument specifies a random number generator, see [Random Numbers](@ref). - -# Examples -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> sprand(rng, Bool, 2, 2, 0.5) -2×2 SparseMatrixCSC{Bool,Int64} with 2 stored entries: - [1, 1] = true - [2, 1] = true - -julia> sprand(rng, Float64, 3, 0.75) -3-element SparseVector{Float64,Int64} with 1 stored entry: - [3] = 0.298614 -``` -""" -function sprand(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat, - rfn::Function, ::Type{T}=eltype(rfn(r,1))) where T - N = m*n - N == 0 && return spzeros(T,m,n) - N == 1 && return rand(r) <= density ? sparse([1], [1], rfn(r,1)) : spzeros(T,1,1) - - I,J = sprand_IJ(r, m, n, density) - sparse_IJ_sorted!(I, J, rfn(r,length(I)), m, n, +) # it will never need to combine -end - -function sprand(m::Integer, n::Integer, density::AbstractFloat, - rfn::Function, ::Type{T}=eltype(rfn(1))) where T - N = m*n - N == 0 && return spzeros(T,m,n) - N == 1 && return rand() <= density ? sparse([1], [1], rfn(1)) : spzeros(T,1,1) - - I,J = sprand_IJ(GLOBAL_RNG, m, n, density) - sparse_IJ_sorted!(I, J, rfn(length(I)), m, n, +) # it will never need to combine -end - -truebools(r::AbstractRNG, n::Integer) = ones(Bool, n) - -sprand(m::Integer, n::Integer, density::AbstractFloat) = sprand(GLOBAL_RNG,m,n,density) - -sprand(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density,rand,Float64) -sprand(r::AbstractRNG, ::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where {T} = sprand(r,m,n,density,(r, i) -> rand(r, T, i), T) -sprand(r::AbstractRNG, ::Type{Bool}, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density, truebools, Bool) -sprand(::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where {T} = sprand(GLOBAL_RNG, T, m, n, density) - -""" - sprandn([rng], m[,n],p::AbstractFloat) - -Create a random sparse vector of length `m` or sparse matrix of size `m` by `n` -with the specified (independent) probability `p` of any entry being nonzero, -where nonzero values are sampled from the normal distribution. The optional `rng` -argument specifies a random number generator, see [Random Numbers](@ref). - -# Examples -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> sprandn(rng, 2, 2, 0.75) -2×2 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 0.532813 - [2, 1] = -0.271735 - [2, 2] = 0.502334 -``` -""" -sprandn(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density,randn,Float64) -sprandn(m::Integer, n::Integer, density::AbstractFloat) = sprandn(GLOBAL_RNG,m,n,density) - """ spones(S) diff --git a/base/sparse/sparsevector.jl b/base/sparse/sparsevector.jl index 293a9d5925954..c36d537605823 100644 --- a/base/sparse/sparsevector.jl +++ b/base/sparse/sparsevector.jl @@ -477,31 +477,6 @@ copy!(A::SparseMatrixCSC, B::SparseVector{TvB,TiB}) where {TvB,TiB} = copy!(A, SparseMatrixCSC{TvB,TiB}(B.n, 1, TiB[1, length(B.nzind)+1], B.nzind, B.nzval)) -### Rand Construction -sprand(n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where {T} = sprand(GLOBAL_RNG, n, p, rfn, T) -function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where T - I = randsubseq(r, 1:convert(Int, n), p) - V = rfn(r, T, length(I)) - SparseVector(n, I, V) -end - -sprand(n::Integer, p::AbstractFloat, rfn::Function) = sprand(GLOBAL_RNG, n, p, rfn) -function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function) - I = randsubseq(r, 1:convert(Int, n), p) - V = rfn(r, length(I)) - SparseVector(n, I, V) -end - -sprand(n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, n, p, rand) - -sprand(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, rand) -sprand(r::AbstractRNG, ::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(r, n, p, (r, i) -> rand(r, T, i)) -sprand(r::AbstractRNG, ::Type{Bool}, n::Integer, p::AbstractFloat) = sprand(r, n, p, truebools) -sprand(::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(GLOBAL_RNG, T, n, p) - -sprandn(n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, n, p, randn) -sprandn(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, randn) - ## Indexing into Matrices can return SparseVectors # Column slices diff --git a/base/sysimg.jl b/base/sysimg.jl index fe9676f4f41f9..ca2a146900e3e 100644 --- a/base/sysimg.jl +++ b/base/sysimg.jl @@ -354,12 +354,6 @@ include("irrationals.jl") include("mathconstants.jl") using .MathConstants: ℯ, π, pi -# random number generation -include("random/dSFMT.jl") -include("random/random.jl") -using .Random -import .Random: rand, rand! - # (s)printf macros include("printf.jl") using .Printf @@ -414,6 +408,9 @@ include("libgit2/libgit2.jl") include("pkg/pkg.jl") # sparse matrices, vectors, and sparse linear algebra + +function _rand_pm1! end # defined in Random + include("sparse/sparse.jl") using .SparseArrays @@ -455,7 +452,14 @@ include("docs/Docs.jl") using .Docs, .Markdown isdefined(Core, :Inference) && Docs.loaddocs(Core.Inference.CoreDocs.DOCS) +# RAND_MAX at least 32767 in theory, but we assume 2^32-1 +Crand() = ccall(:rand, Cuint, ()) +Crand(::Type{UInt32}) = Crand() % UInt32 +Crand(::Type{Float64}) = Crand(UInt32) / 2^32 + function __init__() + # for the few uses of Crand in Base: + ccall(:srand, Void, (Cuint,), floor(time())) # Base library init reinit_stdio() global_logger(SimpleLogger(STDERR)) @@ -479,16 +483,17 @@ Base.require(:Base64) Base.require(:CRC32c) Base.require(:Dates) Base.require(:DelimitedFiles) +Base.require(:Distributed) Base.require(:FileWatching) Base.require(:IterativeEigenSolvers) Base.require(:Logging) Base.require(:Mmap) Base.require(:Profile) +Base.require(:Random) Base.require(:SharedArrays) Base.require(:SuiteSparse) Base.require(:Test) Base.require(:Unicode) -Base.require(:Distributed) @eval Base begin @deprecate_binding Test root_module(:Test) true ", run `using Test` instead" @@ -496,6 +501,7 @@ Base.require(:Distributed) @deprecate_binding Profile root_module(:Profile) true ", run `using Profile` instead" @deprecate_binding Dates root_module(:Dates) true ", run `using Dates` instead" # @deprecate_binding Distributed root_module(:Distributed) true ", run `using Distributed` instead" + @deprecate_binding Random root_module(:Random) true ", run `using Random` instead" end empty!(LOAD_PATH) diff --git a/base/task.jl b/base/task.jl index 26569252e7a87..8037386ed8707 100644 --- a/base/task.jl +++ b/base/task.jl @@ -61,6 +61,8 @@ Wrap an expression in a [`Task`](@ref) without executing it, and return the [`Ta creates a task, and does not run it. ```jldoctest +julia> using Random + julia> a1() = det(rand(1000, 1000)); julia> b = @task a1(); diff --git a/doc/make.jl b/doc/make.jl index a272344ac7ab6..1f5fe7029df65 100644 --- a/doc/make.jl +++ b/doc/make.jl @@ -33,6 +33,7 @@ if Sys.iswindows() cp_q("../stdlib/IterativeEigenSolvers/docs/src/index.md", "src/stdlib/iterativeeigensolvers.md") cp_q("../stdlib/Unicode/docs/src/index.md", "src/stdlib/unicode.md") cp_q("../stdlib/Distributed/docs/src/index.md", "src/stdlib/distributed.md") + cp_q("../stdlib/Random/docs/src/index.md", "src/stdlib/random.md") else symlink_q("../../../stdlib/DelimitedFiles/docs/src/index.md", "src/stdlib/delimitedfiles.md") symlink_q("../../../stdlib/Test/docs/src/index.md", "src/stdlib/test.md") @@ -46,6 +47,7 @@ else symlink_q("../../../stdlib/IterativeEigenSolvers/docs/src/index.md", "src/stdlib/iterativeeigensolvers.md") symlink_q("../../../stdlib/Unicode/docs/src/index.md", "src/stdlib/unicode.md") symlink_q("../../../stdlib/Distributed/docs/src/index.md", "src/stdlib/distributed.md") + symlink_q("../../../stdlib/Random/docs/src/index.md", "src/stdlib/random.md") end const PAGES = [ @@ -125,6 +127,7 @@ const PAGES = [ "stdlib/crc32c.md", "stdlib/iterativeeigensolvers.md", "stdlib/unicode.md", + "stdlib/random.md", ], "Developer Documentation" => [ "devdocs/reflection.md", @@ -160,7 +163,7 @@ const PAGES = [ ] using DelimitedFiles, Test, Mmap, SharedArrays, Profile, Base64, FileWatching, CRC32c, - Dates, IterativeEigenSolvers, Unicode, Distributed + Dates, IterativeEigenSolvers, Unicode, Distributed, Random makedocs( build = joinpath(pwd(), "_build/html/en"), diff --git a/doc/src/stdlib/.gitignore b/doc/src/stdlib/.gitignore index 7096169fbd716..a3beb80750eb5 100644 --- a/doc/src/stdlib/.gitignore +++ b/doc/src/stdlib/.gitignore @@ -8,3 +8,4 @@ filewatching.md crc32c.md dates.md unicode.md +random.md diff --git a/doc/src/stdlib/arrays.md b/doc/src/stdlib/arrays.md index 81d4d7d62e9f9..4a94fe7f54e04 100644 --- a/doc/src/stdlib/arrays.md +++ b/doc/src/stdlib/arrays.md @@ -200,8 +200,6 @@ Base.SparseArrays.nnz Base.SparseArrays.spzeros Base.SparseArrays.spones Base.SparseArrays.spdiagm -Base.SparseArrays.sprand -Base.SparseArrays.sprandn Base.SparseArrays.nonzeros Base.SparseArrays.rowvals Base.SparseArrays.nzrange diff --git a/doc/src/stdlib/numbers.md b/doc/src/stdlib/numbers.md index 9ed0821042869..4be2570374488 100644 --- a/doc/src/stdlib/numbers.md +++ b/doc/src/stdlib/numbers.md @@ -130,38 +130,3 @@ BigFloat(x::Union{Integer, AbstractFloat, String}, rounding::RoundingMode) Base.MPFR.BigFloat(x, prec::Int, rounding::RoundingMode) Base.MPFR.BigFloat(x::String) ``` - -## Random Numbers - -Random number generation in Julia uses the [Mersenne Twister library](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/#dSFMT) -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`](@ref), [`Float32`](@ref), [`Float64`](@ref), [`BigFloat`](@ref), [`Bool`](@ref), -[`Int8`](@ref), [`UInt8`](@ref), [`Int16`](@ref), [`UInt16`](@ref), [`Int32`](@ref), -[`UInt32`](@ref), [`Int64`](@ref), [`UInt64`](@ref), [`Int128`](@ref), [`UInt128`](@ref), -[`BigInt`](@ref) (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))`). - -```@docs -Base.Random.srand -Base.Random.MersenneTwister -Base.Random.RandomDevice -Base.Random.rand -Base.Random.rand! -Base.Random.bitrand -Base.Random.randn -Base.Random.randn! -Base.Random.randexp -Base.Random.randexp! -Base.Random.randjump -``` diff --git a/stdlib/Base64/test/runtests.jl b/stdlib/Base64/test/runtests.jl index 8eab331ee6b1b..405ccb830bb67 100644 --- a/stdlib/Base64/test/runtests.jl +++ b/stdlib/Base64/test/runtests.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random import Base64: Base64EncodePipe, base64encode, diff --git a/stdlib/CRC32c/test/runtests.jl b/stdlib/CRC32c/test/runtests.jl index 4f0fefe93c747..d672514496f18 100644 --- a/stdlib/CRC32c/test/runtests.jl +++ b/stdlib/CRC32c/test/runtests.jl @@ -1,4 +1,4 @@ -using Test +using Test, Random using CRC32c function test_crc32c(crc32c) @@ -60,4 +60,3 @@ end crc32c_sw(io::IO, crc::UInt32=0x00000000) = crc32c_sw(io, typemax(Int64), crc) test_crc32c(crc32c) test_crc32c(crc32c_sw) - diff --git a/stdlib/DelimitedFiles/test/runtests.jl b/stdlib/DelimitedFiles/test/runtests.jl index a1731ee1c82a3..de45de722028a 100644 --- a/stdlib/DelimitedFiles/test/runtests.jl +++ b/stdlib/DelimitedFiles/test/runtests.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using DelimitedFiles isequaldlm(m1, m2, t) = isequal(m1, m2) && (eltype(m1) == eltype(m2) == t) diff --git a/stdlib/Distributed/src/cluster.jl b/stdlib/Distributed/src/cluster.jl index e658d639664c1..90c1e8f8d0794 100644 --- a/stdlib/Distributed/src/cluster.jl +++ b/stdlib/Distributed/src/cluster.jl @@ -1114,6 +1114,8 @@ function init_bind_addr() LPROC.bind_port = UInt16(bind_port) end +using Random: randstring + function init_parallel() start_gc_msgs_task() atexit(terminate_all_workers) diff --git a/stdlib/Distributed/test/distributed_exec.jl b/stdlib/Distributed/test/distributed_exec.jl index 80112777bb264..d3d9ec25d51ac 100644 --- a/stdlib/Distributed/test/distributed_exec.jl +++ b/stdlib/Distributed/test/distributed_exec.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test, Distributed +using Test, Distributed, Random import Distributed: launch, manage include(joinpath(JULIA_HOME, "..", "share", "julia", "test", "testenv.jl")) @@ -1498,4 +1498,3 @@ end # cluster at any time only supports a single topology. rmprocs(workers()) include("topology.jl") - diff --git a/stdlib/Distributed/test/topology.jl b/stdlib/Distributed/test/topology.jl index ff898351d3f52..e35115636002c 100644 --- a/stdlib/Distributed/test/topology.jl +++ b/stdlib/Distributed/test/topology.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + pids = addprocs_with_testenv(4; topology="master_slave") let p1 = pids[1], p2 = pids[2] diff --git a/stdlib/IterativeEigenSolvers/test/runtests.jl b/stdlib/IterativeEigenSolvers/test/runtests.jl index 833d1d5124079..0bb65c476fe9a 100644 --- a/stdlib/IterativeEigenSolvers/test/runtests.jl +++ b/stdlib/IterativeEigenSolvers/test/runtests.jl @@ -1,7 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using IterativeEigenSolvers -using Test +using Test, Random @testset "eigs" begin guardsrand(1234) do diff --git a/stdlib/Mmap/test/runtests.jl b/stdlib/Mmap/test/runtests.jl index ee77f392f4c72..7ca20e7aa42b3 100644 --- a/stdlib/Mmap/test/runtests.jl +++ b/stdlib/Mmap/test/runtests.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test, Mmap +using Test, Mmap, Random file = tempname() write(file, "Hello World\n") diff --git a/stdlib/Random/docs/src/index.md b/stdlib/Random/docs/src/index.md new file mode 100644 index 0000000000000..387ca32f5543e --- /dev/null +++ b/stdlib/Random/docs/src/index.md @@ -0,0 +1,36 @@ +# Random Numbers + +Random number generation in Julia uses the [Mersenne Twister library](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/#dSFMT) +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`](@ref), [`Float32`](@ref), [`Float64`](@ref), [`BigFloat`](@ref), [`Bool`](@ref), +[`Int8`](@ref), [`UInt8`](@ref), [`Int16`](@ref), [`UInt16`](@ref), [`Int32`](@ref), +[`UInt32`](@ref), [`Int64`](@ref), [`UInt64`](@ref), [`Int128`](@ref), [`UInt128`](@ref), +[`BigInt`](@ref) (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))`). + +```@docs +Random.srand +Random.MersenneTwister +Random.RandomDevice +Random.rand +Random.rand! +Random.bitrand +Random.randn +Random.randn! +Random.randexp +Random.randexp! +Random.randjump +Random.sprand +Random.sprandn +``` diff --git a/base/random/RNGs.jl b/stdlib/Random/src/RNGs.jl similarity index 98% rename from base/random/RNGs.jl rename to stdlib/Random/src/RNGs.jl index 8156c39b76196..3babe38a6bc53 100644 --- a/base/random/RNGs.jl +++ b/stdlib/Random/src/RNGs.jl @@ -27,6 +27,16 @@ else # !windows end rand(rd::RandomDevice, sp::SamplerBoolBitInteger) = read( rd.file, sp[]) + + function serialize(s::AbstractSerializer, rd::RandomDevice) + Serializer.serialize_type(s, typeof(rd)) + serialize(s, rd.unlimited) + end + function deserialize(s::AbstractSerializer, t::Type{RandomDevice}) + unlimited = deserialize(s) + return RandomDevice(unlimited) + end + end # os-test # NOTE: this can't be put within the if-else block above diff --git a/base/random/random.jl b/stdlib/Random/src/Random.jl similarity index 93% rename from base/random/random.jl rename to stdlib/Random/src/Random.jl index d17964a62032d..92542c73353bf 100644 --- a/base/random/random.jl +++ b/stdlib/Random/src/Random.jl @@ -1,16 +1,21 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +__precompile__(true) + module Random -using Base.dSFMT +include("dSFMT.jl") + +using .dSFMT using Base.GMP: Limb, MPZ using Base: BitInteger, BitInteger_types, BitUnsigned, @gc_preserve -import Base: copymutable, copy, copy!, ==, hash +import Base: copymutable, copy, copy!, ==, hash, serialize, deserialize export srand, rand, rand!, randn, randn!, + sprand, sprandn, randexp, randexp!, bitrand, randstring, @@ -19,8 +24,9 @@ export srand, randperm, randperm!, randcycle, randcycle!, AbstractRNG, MersenneTwister, RandomDevice, - GLOBAL_RNG, randjump + GLOBAL_RNG, defaultRNG, randjump +defaultRNG() = GLOBAL_RNG ## general definitions @@ -63,6 +69,7 @@ for UI = (:UInt10, :UInt10Raw, :UInt23, :UInt23Raw, :UInt52, :UInt52Raw, end end + ### floats abstract type FloatInterval{T<:AbstractFloat} end @@ -237,7 +244,7 @@ include("RNGs.jl") include("generation.jl") include("normal.jl") include("misc.jl") - +include("sparse.jl") ## rand & rand! & srand docstrings @@ -348,4 +355,13 @@ true """ srand(rng::AbstractRNG, ::Void) = srand(rng) + +## deprecations + +# PR #21359 + +@deprecate srand(r::MersenneTwister, filename::AbstractString, n::Integer=4) srand(r, read!(filename, Vector{UInt32}(uninitialized, Int(n)))) +@deprecate srand(filename::AbstractString, n::Integer=4) srand(read!(filename, Vector{UInt32}(uninitialized, Int(n)))) +@deprecate MersenneTwister(filename::AbstractString) srand(MersenneTwister(0), read!(filename, Vector{UInt32}(uninitialized, Int(4)))) + end # module diff --git a/base/random/dSFMT.jl b/stdlib/Random/src/dSFMT.jl similarity index 100% rename from base/random/dSFMT.jl rename to stdlib/Random/src/dSFMT.jl diff --git a/base/random/generation.jl b/stdlib/Random/src/generation.jl similarity index 100% rename from base/random/generation.jl rename to stdlib/Random/src/generation.jl diff --git a/base/random/misc.jl b/stdlib/Random/src/misc.jl similarity index 99% rename from base/random/misc.jl rename to stdlib/Random/src/misc.jl index e9b3cfbb19346..07041f1ed506e 100644 --- a/base/random/misc.jl +++ b/stdlib/Random/src/misc.jl @@ -362,7 +362,7 @@ according to section 4.5 of the RFC. ```jldoctest julia> rng = MersenneTwister(1234); -julia> Base.Random.uuid1(rng) +julia> Random.uuid1(rng) 2cc938da-5937-11e7-196e-0f4ef71aa64b ``` """ @@ -399,7 +399,7 @@ as specified by RFC 4122. ```jldoctest julia> rng = MersenneTwister(1234); -julia> Base.Random.uuid4(rng) +julia> Random.uuid4(rng) 82015f10-44cc-4827-996e-0f4ef71aa64b ``` """ @@ -419,7 +419,7 @@ Inspects the given UUID and returns its version (see RFC 4122). ```jldoctest julia> rng = MersenneTwister(1234); -julia> Base.Random.uuid_version(Base.Random.uuid4(rng)) +julia> Random.uuid_version(Random.uuid4(rng)) 4 ``` """ diff --git a/base/random/normal.jl b/stdlib/Random/src/normal.jl similarity index 100% rename from base/random/normal.jl rename to stdlib/Random/src/normal.jl diff --git a/stdlib/Random/src/sparse.jl b/stdlib/Random/src/sparse.jl new file mode 100644 index 0000000000000..01c88d7798b34 --- /dev/null +++ b/stdlib/Random/src/sparse.jl @@ -0,0 +1,155 @@ +# This file is a part of Julia. License is MIT: https://julialang.org/license + + +## matrices + +function sprand_IJ(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) + ((m < 0) || (n < 0)) && throw(ArgumentError("invalid Array dimensions")) + 0 <= density <= 1 || throw(ArgumentError("$density not in [0,1]")) + N = n*m + + I, J = Vector{Int}(), Vector{Int}() # indices of nonzero elements + sizehint!(I, round(Int,N*density)) + sizehint!(J, round(Int,N*density)) + + # density of nonzero columns: + L = log1p(-density) + coldensity = -expm1(m*L) # = 1 - (1-density)^m + colsparsity = exp(m*L) # = 1 - coldensity + iL = 1/L + + rows = Vector{Int}() + for j in randsubseq(r, 1:n, coldensity) + # To get the right statistics, we *must* have a nonempty column j + # even if p*m << 1. To do this, we use an approach similar to + # the one in randsubseq to compute the expected first nonzero row k, + # except given that at least one is nonzero (via Bayes' rule); + # carefully rearranged to avoid excessive roundoff errors. + k = ceil(log(colsparsity + rand(r)*coldensity) * iL) + ik = k < 1 ? 1 : k > m ? m : Int(k) # roundoff-error/underflow paranoia + randsubseq!(r, rows, 1:m-ik, density) + push!(rows, m-ik+1) + append!(I, rows) + nrows = length(rows) + Jlen = length(J) + resize!(J, Jlen+nrows) + @inbounds for i = Jlen+1:length(J) + J[i] = j + end + end + I, J +end + + +""" + sprand([rng],[type],m,[n],p::AbstractFloat,[rfn]) + +Create a random length `m` sparse vector or `m` by `n` sparse matrix, in +which the probability of any element being nonzero is independently given by +`p` (and hence the mean density of nonzeros is also exactly `p`). Nonzero +values are sampled from the distribution specified by `rfn` and have the type `type`. The uniform +distribution is used in case `rfn` is not specified. The optional `rng` +argument specifies a random number generator, see [Random Numbers](@ref). + +# Examples +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> sprand(rng, Bool, 2, 2, 0.5) +2×2 SparseMatrixCSC{Bool,Int64} with 2 stored entries: + [1, 1] = true + [2, 1] = true + +julia> sprand(rng, Float64, 3, 0.75) +3-element SparseVector{Float64,Int64} with 1 stored entry: + [3] = 0.298614 +``` +""" +function sprand(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat, + rfn::Function, ::Type{T}=eltype(rfn(r,1))) where T + N = m*n + N == 0 && return spzeros(T,m,n) + N == 1 && return rand(r) <= density ? sparse([1], [1], rfn(r,1)) : spzeros(T,1,1) + + I,J = sprand_IJ(r, m, n, density) + sparse_IJ_sorted!(I, J, rfn(r,length(I)), m, n, +) # it will never need to combine +end + +function sprand(m::Integer, n::Integer, density::AbstractFloat, + rfn::Function, ::Type{T}=eltype(rfn(1))) where T + N = m*n + N == 0 && return spzeros(T,m,n) + N == 1 && return rand() <= density ? sparse([1], [1], rfn(1)) : spzeros(T,1,1) + + I,J = sprand_IJ(defaultRNG(), m, n, density) + sparse_IJ_sorted!(I, J, rfn(length(I)), m, n, +) # it will never need to combine +end + +truebools(r::AbstractRNG, n::Integer) = ones(Bool, n) + +sprand(m::Integer, n::Integer, density::AbstractFloat) = sprand(defaultRNG(),m,n,density) + +sprand(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density,rand,Float64) +sprand(r::AbstractRNG, ::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where {T} = sprand(r,m,n,density,(r, i) -> rand(r, T, i), T) +sprand(r::AbstractRNG, ::Type{Bool}, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density, truebools, Bool) +sprand(::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where {T} = sprand(defaultRNG(), T, m, n, density) + +""" + sprandn([rng], m[,n],p::AbstractFloat) + +Create a random sparse vector of length `m` or sparse matrix of size `m` by `n` +with the specified (independent) probability `p` of any entry being nonzero, +where nonzero values are sampled from the normal distribution. The optional `rng` +argument specifies a random number generator, see [Random Numbers](@ref). + +# Examples +```jldoctest +julia> rng = MersenneTwister(1234); + +julia> sprandn(rng, 2, 2, 0.75) +2×2 SparseMatrixCSC{Float64,Int64} with 3 stored entries: + [1, 1] = 0.532813 + [2, 1] = -0.271735 + [2, 2] = 0.502334 +``` +""" +sprandn(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density,randn,Float64) +sprandn(m::Integer, n::Integer, density::AbstractFloat) = sprandn(defaultRNG(),m,n,density) + + +## vectors + + +### Rand Construction +sprand(n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where {T} = sprand(defaultRNG(), n, p, rfn, T) +function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where T + I = randsubseq(r, 1:convert(Int, n), p) + V = rfn(r, T, length(I)) + SparseVector(n, I, V) +end + +sprand(n::Integer, p::AbstractFloat, rfn::Function) = sprand(defaultRNG(), n, p, rfn) +function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function) + I = randsubseq(r, 1:convert(Int, n), p) + V = rfn(r, length(I)) + SparseVector(n, I, V) +end + +sprand(n::Integer, p::AbstractFloat) = sprand(defaultRNG(), n, p, rand) + +sprand(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, rand) +sprand(r::AbstractRNG, ::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(r, n, p, (r, i) -> rand(r, T, i)) +sprand(r::AbstractRNG, ::Type{Bool}, n::Integer, p::AbstractFloat) = sprand(r, n, p, truebools) +sprand(::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(defaultRNG(), T, n, p) + +sprandn(n::Integer, p::AbstractFloat) = sprand(defaultRNG(), n, p, randn) +sprandn(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, randn) + + +## _rand_pm1! (used in Base.LinAlg) + +function Base._rand_pm1!(v) + for i in eachindex(v) + v[i] = rand(Bool) ? 1 : -1 + end +end diff --git a/test/random.jl b/stdlib/Random/test/runtests.jl similarity index 95% rename from test/random.jl rename to stdlib/Random/test/runtests.jl index 9130c306de94e..5c52929b8733c 100644 --- a/test/random.jl +++ b/stdlib/Random/test/runtests.jl @@ -1,9 +1,12 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) +using Test + +isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "../../../test/TestHelpers.jl")) using Main.TestHelpers.OAs -using Base.Random: Sampler, SamplerRangeFast, SamplerRangeInt +using Random +using Random: dSFMT, Sampler, SamplerRangeFast, SamplerRangeInt # Issue #6573 guardsrand(0) do @@ -92,10 +95,10 @@ for T in (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt end end -@test !any([(Base.Random.maxmultiple(i)+i) > 0xFF for i in 0x00:0xFF]) -@test all([(Base.Random.maxmultiple(i)+1) % i for i in 0x01:0xFF] .== 0) -@test all([(Base.Random.maxmultiple(i)+1+i) > 0xFF for i in 0x00:0xFF]) -@test length(0x00:0xFF)== Base.Random.maxmultiple(0x0)+1 +@test !any([(Random.maxmultiple(i)+i) > 0xFF for i in 0x00:0xFF]) +@test all([(Random.maxmultiple(i)+1) % i for i in 0x01:0xFF] .== 0) +@test all([(Random.maxmultiple(i)+1+i) > 0xFF for i in 0x00:0xFF]) +@test length(0x00:0xFF)== Random.maxmultiple(0x0)+1 if sizeof(Int32) < sizeof(Int) @@ -108,7 +111,6 @@ if sizeof(Int32) < sizeof(Int) @test all(div(one(UInt128) << 64, k)*k - 1 == SamplerRangeInt(map(U, 1:k)).u for k in 13 .+ Int64(2).^(52:62)) end - end # BigInt specific @@ -205,12 +207,12 @@ function randmtzig_fill_ziggurat_tables() # Operates on the global arrays return nothing end randmtzig_fill_ziggurat_tables() -@test all(ki == Base.Random.ki) -@test all(wi == Base.Random.wi) -@test all(fi == Base.Random.fi) -@test all(ke == Base.Random.ke) -@test all(we == Base.Random.we) -@test all(fe == Base.Random.fe) +@test all(ki == Random.ki) +@test all(wi == Random.wi) +@test all(fi == Random.fi) +@test all(ke == Random.ke) +@test all(we == Random.we) +@test all(fe == Random.fe) #same random numbers on for small ranges on all systems guardsrand() do @@ -231,7 +233,7 @@ for U in (Int64, UInt64) end -import Base.Random: uuid1, uuid4, UUID, uuid_version +import Random: uuid1, uuid4, UUID, uuid_version # UUID u1 = uuid1() @@ -286,12 +288,12 @@ let mt = MersenneTwister(0) end srand(mt, 0) - AF64 = Vector{Float64}(uninitialized, Base.Random.dsfmt_get_min_array_size()-1) + AF64 = Vector{Float64}(uninitialized, Random.dsfmt_get_min_array_size()-1) @test rand!(mt, AF64)[end] == 0.957735065345398 @test rand!(mt, AF64)[end] == 0.6492481059865669 resize!(AF64, 2*length(mt.vals)) - @test invoke(rand!, Tuple{MersenneTwister,AbstractArray{Float64},Base.Random.SamplerTrivial{Base.Random.CloseOpen_64}}, - mt, AF64, Base.Random.SamplerTrivial(Base.Random.CloseOpen()))[end] == 0.432757268470779 + @test invoke(rand!, Tuple{MersenneTwister,AbstractArray{Float64},Random.SamplerTrivial{Random.CloseOpen_64}}, + mt, AF64, Random.SamplerTrivial(Random.CloseOpen()))[end] == 0.432757268470779 end # Issue #9037 @@ -559,11 +561,11 @@ let seed = rand(UInt32, 10) end # MersenneTwister initialization with invalid values -@test_throws DomainError Base.dSFMT.DSFMT_state(zeros(Int32, rand(0:Base.dSFMT.JN32-1))) -@test_throws DomainError MersenneTwister(zeros(UInt32, 1), Base.dSFMT.DSFMT_state(), +@test_throws DomainError dSFMT.DSFMT_state(zeros(Int32, rand(0:dSFMT.JN32-1))) +@test_throws DomainError MersenneTwister(zeros(UInt32, 1), dSFMT.DSFMT_state(), zeros(Float64, 10), 0) -@test_throws DomainError MersenneTwister(zeros(UInt32, 1), Base.dSFMT.DSFMT_state(), - zeros(Float64, Base.Random.MTCacheLength), -1) +@test_throws DomainError MersenneTwister(zeros(UInt32, 1), dSFMT.DSFMT_state(), + zeros(Float64, Random.MTCacheLength), -1) # seed is private to MersenneTwister let seed = rand(UInt32, 10) @@ -581,7 +583,7 @@ end # srand(rng, ...) returns rng (#21248) guardsrand() do - g = Base.Random.GLOBAL_RNG + g = Random.GLOBAL_RNG m = MersenneTwister(0) @test srand() === g @test srand(rand(UInt)) === g @@ -594,8 +596,8 @@ end # Issue 20062 - ensure internal functions reserve_1, reserve are type-stable let r = MersenneTwister(0) - @inferred Base.Random.reserve_1(r) - @inferred Base.Random.reserve(r, 1) + @inferred Random.reserve_1(r) + @inferred Random.reserve(r, 1) end # test randstring API diff --git a/stdlib/SharedArrays/src/SharedArrays.jl b/stdlib/SharedArrays/src/SharedArrays.jl index 4f7366df40957..c1481c33f8a58 100644 --- a/stdlib/SharedArrays/src/SharedArrays.jl +++ b/stdlib/SharedArrays/src/SharedArrays.jl @@ -7,11 +7,11 @@ Provide the [`SharedArray`](@ref) type. It represents an array, which is shared """ module SharedArrays -using Mmap, Distributed +using Mmap, Distributed, Random import Base: length, size, ndims, IndexStyle, reshape, convert, deepcopy_internal, serialize, deserialize, - show, getindex, setindex!, fill!, rand!, similar, reduce, map!, copy!, unsafe_convert -import Base.Random + show, getindex, setindex!, fill!, similar, reduce, map!, copy!, unsafe_convert +import Random import Base.Serializer: serialize_cycle_header, serialize_type, writetag, UNDEFREF_TAG import Distributed: RRID, procs import Base.Filesystem: JL_O_CREAT, JL_O_RDWR, S_IRUSR, S_IWUSR @@ -506,7 +506,7 @@ function fill!(S::SharedArray, v) return S end -function rand!(S::SharedArray{T}) where T +function Random.rand!(S::SharedArray{T}) where T f = S->map!(x -> rand(T), S.loc_subarr_1d, S.loc_subarr_1d) @sync for p in procs(S) @async remotecall_wait(f, p, S) diff --git a/stdlib/SharedArrays/test/runtests.jl b/stdlib/SharedArrays/test/runtests.jl index 6b62a645d404c..94f2c149e7824 100644 --- a/stdlib/SharedArrays/test/runtests.jl +++ b/stdlib/SharedArrays/test/runtests.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test, Distributed, SharedArrays +using Test, Distributed, SharedArrays, Random include(joinpath(JULIA_HOME, "..", "share", "julia", "test", "testenv.jl")) addprocs_with_testenv(4) diff --git a/stdlib/SuiteSparse/test/runtests.jl b/stdlib/SuiteSparse/test/runtests.jl index f27f76068991a..9a13b39b5eb3d 100644 --- a/stdlib/SuiteSparse/test/runtests.jl +++ b/stdlib/SuiteSparse/test/runtests.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using SuiteSparse if Base.USE_GPL_LIBS diff --git a/stdlib/Test/src/Test.jl b/stdlib/Test/src/Test.jl index a848bd85eb52d..ca234350ea67f 100644 --- a/stdlib/Test/src/Test.jl +++ b/stdlib/Test/src/Test.jl @@ -18,6 +18,7 @@ module Test export @test, @test_throws, @test_broken, @test_skip, @test_warn, @test_nowarn, @test_logs, @test_deprecated + export @testset # Legacy approximate testing functions, yet to be included export @inferred @@ -25,6 +26,8 @@ export detect_ambiguities, detect_unbound_args export GenericString, GenericSet, GenericDict, GenericArray export guardsrand +using Random: srand, defaultRNG, AbstractRNG + #----------------------------------------------------------------------- # Backtrace utility functions @@ -1466,7 +1469,7 @@ Base.similar(A::GenericArray, s::Integer...) = GenericArray(similar(A.a, s...)) "`guardsrand(f)` runs the function `f()` and then restores the state of the global RNG as it was before." -function guardsrand(f::Function, r::AbstractRNG=Base.GLOBAL_RNG) +function guardsrand(f::Function, r::AbstractRNG=defaultRNG()) old = copy(r) try f() diff --git a/test/abstractarray.jl b/test/abstractarray.jl index b74b8bc6b15fa..2e38dc442b0b2 100644 --- a/test/abstractarray.jl +++ b/test/abstractarray.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + A = rand(5,4,3) @testset "Bounds checking" begin @test checkbounds(Bool, A, 1, 1, 1) == true diff --git a/test/arrayops.jl b/test/arrayops.jl index be890b7dec886..33253585524cc 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -4,6 +4,8 @@ isdefined(Main, :TestHelpers) || @eval Main include("TestHelpers.jl") using Main.TestHelpers.OAs +using Random + @testset "basics" begin @test length([1, 2, 3]) == 3 @test count(!iszero, [1, 2, 3]) == 3 diff --git a/test/asyncmap.jl b/test/asyncmap.jl index c8b514f2bc890..6ab62bd231cd0 100644 --- a/test/asyncmap.jl +++ b/test/asyncmap.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # Test asyncmap @test allunique(asyncmap(x->(sleep(1.0);object_id(current_task())), 1:10)) diff --git a/test/bigint.jl b/test/bigint.jl index dddcc66c467fd..0c29a8a961aa9 100644 --- a/test/bigint.jl +++ b/test/bigint.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + a = parse(BigInt,"123456789012345678901234567890") b = parse(BigInt,"123456789012345678901234567891") c = parse(BigInt,"246913578024691357802469135780") diff --git a/test/bitarray.jl b/test/bitarray.jl index 366e37d9f15b7..f08d561cfb9ba 100644 --- a/test/bitarray.jl +++ b/test/bitarray.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base: findprevnot, findnextnot +using Random tc(r1::NTuple{N,Any}, r2::NTuple{N,Any}) where {N} = all(x->tc(x...), [zip(r1,r2)...]) tc(r1::BitArray{N}, r2::Union{BitArray{N},Array{Bool,N}}) where {N} = true diff --git a/test/bitset.jl b/test/bitset.jl index a7b4e3e061f29..49e6db84be862 100644 --- a/test/bitset.jl +++ b/test/bitset.jl @@ -2,6 +2,8 @@ # Test functionality of BitSet +using Random + @testset "Construction, collect" begin data_in = (1,5,100) s = BitSet(data_in) diff --git a/test/boundscheck_exec.jl b/test/boundscheck_exec.jl index ee8413bd4e5b9..138059d8fcb8a 100644 --- a/test/boundscheck_exec.jl +++ b/test/boundscheck_exec.jl @@ -2,7 +2,7 @@ module TestBoundsCheck -using Test +using Test, Random @enum BCOption bc_default bc_on bc_off bc_opt = BCOption(Base.JLOptions().check_bounds) diff --git a/test/broadcast.jl b/test/broadcast.jl index 444b088012772..455c7451c00d4 100644 --- a/test/broadcast.jl +++ b/test/broadcast.jl @@ -4,7 +4,7 @@ module TestBroadcastInternals using Base.Broadcast: check_broadcast_indices, check_broadcast_shape, newindex, _bcs using Base: OneTo -using Test +using Test, Random @test @inferred(_bcs((3,5), (3,5))) == (3,5) @test @inferred(_bcs((3,1), (3,5))) == (3,5) diff --git a/test/ccall.jl b/test/ccall.jl index 770f6c0763ba8..4fbbd86c85eb3 100644 --- a/test/ccall.jl +++ b/test/ccall.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license import Base.copy, Base.== +using Random const libccalltest = "libccalltest" diff --git a/test/channels.jl b/test/channels.jl index e70fe0b679189..24e789330df79 100644 --- a/test/channels.jl +++ b/test/channels.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # Test various constructors let c = Channel(1) @test eltype(c) == Any diff --git a/test/choosetests.jl b/test/choosetests.jl index aa8e1ceb31800..4572098adb825 100644 --- a/test/choosetests.jl +++ b/test/choosetests.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + const STDLIB_DIR = joinpath(JULIA_HOME, "..", "share", "julia", "site", "v$(VERSION.major).$(VERSION.minor)") const STDLIBS = readdir(STDLIB_DIR) diff --git a/test/codegen.jl b/test/codegen.jl index 7664b90d29854..686965329dace 100644 --- a/test/codegen.jl +++ b/test/codegen.jl @@ -2,6 +2,8 @@ # tests for codegen and optimizations +using Random + const opt_level = Base.JLOptions().opt_level const coverage = (Base.JLOptions().code_coverage > 0) || (Base.JLOptions().malloc_log > 0) const Iptr = sizeof(Int) == 8 ? "i64" : "i32" diff --git a/test/combinatorics.jl b/test/combinatorics.jl index 9713d89fa9035..95f3ab9f85a38 100644 --- a/test/combinatorics.jl +++ b/test/combinatorics.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random: randcycle + @testset "binomial" begin @test binomial(5,-1) == 0 @test binomial(5,10) == 0 diff --git a/test/compile.jl b/test/compile.jl index daafb6091e8c6..0bbadd8c2cbe7 100644 --- a/test/compile.jl +++ b/test/compile.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test, Distributed +using Test, Distributed, Random import Base: root_module diff --git a/test/copy.jl b/test/copy.jl index 103ad6c849d81..ad5b4c95dd977 100644 --- a/test/copy.jl +++ b/test/copy.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + mainres = ([4, 5, 3], [1, 5, 3]) bitres = ([true, true, false], diff --git a/test/core.jl b/test/core.jl index 254ccdd38afb8..08e9f60d302fb 100644 --- a/test/core.jl +++ b/test/core.jl @@ -1,6 +1,9 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license # test core language features + +using Random + const Bottom = Union{} # For curmod_* diff --git a/test/dict.jl b/test/dict.jl index f867203a2e506..606edcd79bed6 100644 --- a/test/dict.jl +++ b/test/dict.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @testset "Pair" begin p = Pair(10,20) @test p == (10=>20) diff --git a/test/env.jl b/test/env.jl index ea24759aa5941..2ea6eedafd67c 100644 --- a/test/env.jl +++ b/test/env.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @test !("f=a=k=e=n=a=m=e" ∈ keys(ENV)) @testset "issue #10994" begin diff --git a/test/examples.jl b/test/examples.jl index decb7f7bdf9b4..e53463b393543 100644 --- a/test/examples.jl +++ b/test/examples.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + dir = joinpath(JULIA_HOME, Base.DOCDIR, "examples") include(joinpath(dir, "bubblesort.jl")) diff --git a/test/floatfuncs.jl b/test/floatfuncs.jl index f5f0f7472935a..b686c45b4186c 100644 --- a/test/floatfuncs.jl +++ b/test/floatfuncs.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random # test the basic floating point functions diff --git a/test/hashing.jl b/test/hashing.jl index 67947d74bfeb6..be814bcf3d566 100644 --- a/test/hashing.jl +++ b/test/hashing.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + types = Any[ Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float32, Float64, diff --git a/test/inference.jl b/test/inference.jl index 800f5228cbb96..fa78d54aca771 100644 --- a/test/inference.jl +++ b/test/inference.jl @@ -4,6 +4,8 @@ import Core.Inference: Const, Conditional, ⊑ const isleaftype = Core.Inference._isleaftype +using Random + # demonstrate some of the type-size limits @test Core.Inference.limit_type_size(Ref{Complex{T} where T}, Ref, Ref, 0) == Ref @test Core.Inference.limit_type_size(Ref{Complex{T} where T}, Ref{Complex{T} where T}, Ref, 0) == Ref{Complex{T} where T} diff --git a/test/int.jl b/test/int.jl index ba4c998bdc4bb..48d59ccb504d4 100644 --- a/test/int.jl +++ b/test/int.jl @@ -2,6 +2,7 @@ # Test integer conversion routines from int.jl +using Random for y in (-4, Float32(-4), -4.0, big(-4.0)) @test flipsign(3, y) == -3 diff --git a/test/intfuncs.jl b/test/intfuncs.jl index 062d1103c530f..16db119780a32 100644 --- a/test/intfuncs.jl +++ b/test/intfuncs.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @testset "gcd/lcm" begin # Int32 and Int64 take different code paths -- test both for T in (Int32, Int64) diff --git a/test/iobuffer.jl b/test/iobuffer.jl index 00de2463ad727..6d8d837f478bf 100644 --- a/test/iobuffer.jl +++ b/test/iobuffer.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + ioslength(io::IOBuffer) = (io.seekable ? io.size : nb_available(io)) bufcontents(io::Base.GenericIOBuffer) = unsafe_string(pointer(io.data), io.size) diff --git a/test/iterators.jl b/test/iterators.jl index df453cc5f0c6b..8310fb7acba8e 100644 --- a/test/iterators.jl +++ b/test/iterators.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base.Iterators +using Random # zip and filter iterators # issue #4718 diff --git a/test/libgit2-online.jl b/test/libgit2-online.jl index 27dcd76374f85..16f7b18779e42 100644 --- a/test/libgit2-online.jl +++ b/test/libgit2-online.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + ######### # TESTS # ######### diff --git a/test/libgit2.jl b/test/libgit2.jl index b008bd3ed1480..9e5ee9b30cf22 100644 --- a/test/libgit2.jl +++ b/test/libgit2.jl @@ -4,6 +4,8 @@ isdefined(Main, :TestHelpers) || @eval Main include(joinpath(@__DIR__, "TestHelp import Main.TestHelpers: challenge_prompt using Base.Unicode: lowercase +using Random + const LIBGIT2_MIN_VER = v"0.23.0" const LIBGIT2_HELPER_PATH = joinpath(@__DIR__, "libgit2-helpers.jl") diff --git a/test/linalg/bidiag.jl b/test/linalg/bidiag.jl index 5814775fa3986..ede4d2f41cfa1 100644 --- a/test/linalg/bidiag.jl +++ b/test/linalg/bidiag.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: mul!, Adjoint, Transpose import Base.LinAlg: BlasReal, BlasFloat diff --git a/test/linalg/blas.jl b/test/linalg/blas.jl index 752e896cf3ff3..193815e4fb457 100644 --- a/test/linalg/blas.jl +++ b/test/linalg/blas.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + import Base.LinAlg, Base.LinAlg.BlasReal, Base.LinAlg.BlasComplex srand(100) diff --git a/test/linalg/bunchkaufman.jl b/test/linalg/bunchkaufman.jl index 4d24e6dbbcf07..50122da70671f 100644 --- a/test/linalg/bunchkaufman.jl +++ b/test/linalg/bunchkaufman.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted diff --git a/test/linalg/cholesky.jl b/test/linalg/cholesky.jl index 09d56e19f8037..335762c11f330 100644 --- a/test/linalg/cholesky.jl +++ b/test/linalg/cholesky.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted, PosDefException diff --git a/test/linalg/dense.jl b/test/linalg/dense.jl index e7c7d6d31e01d..291774b993ebb 100644 --- a/test/linalg/dense.jl +++ b/test/linalg/dense.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random @testset "Check that non-floats are correctly promoted" begin @test [1 0 0; 0 1 0]\[1,1] ≈ [1;1;0] diff --git a/test/linalg/diagonal.jl b/test/linalg/diagonal.jl index 014f89bbbf251..f0e77e57652d6 100644 --- a/test/linalg/diagonal.jl +++ b/test/linalg/diagonal.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: mul!, ldiv!, rdiv!, Adjoint, Transpose import Base.LinAlg: BlasFloat, BlasComplex, SingularException diff --git a/test/linalg/eigen.jl b/test/linalg/eigen.jl index a5c224f9f1489..7bd2aeedb669e 100644 --- a/test/linalg/eigen.jl +++ b/test/linalg/eigen.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted diff --git a/test/linalg/generic.jl b/test/linalg/generic.jl index 638a3c8d88478..dded254d80bcc 100644 --- a/test/linalg/generic.jl +++ b/test/linalg/generic.jl @@ -1,7 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license import Base: -, *, /, \ -using Test +using Test, Random # A custom Quaternion type with minimal defined interface and methods. # Used to test scale and scale! methods to show non-commutativity. @@ -436,4 +436,4 @@ end @test !isdiag(lbidiag) @test isdiag(adiag) end -end \ No newline at end of file +end diff --git a/test/linalg/givens.jl b/test/linalg/givens.jl index daa7ef1723318..fe2aa1785226f 100644 --- a/test/linalg/givens.jl +++ b/test/linalg/givens.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: mul!, Adjoint, Transpose # Test givens rotations diff --git a/test/linalg/hessenberg.jl b/test/linalg/hessenberg.jl index 6f0ff890f4ff2..e46b92d34fe13 100644 --- a/test/linalg/hessenberg.jl +++ b/test/linalg/hessenberg.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted diff --git a/test/linalg/lapack.jl b/test/linalg/lapack.jl index 889841935671a..624030efca480 100644 --- a/test/linalg/lapack.jl +++ b/test/linalg/lapack.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random import Base.LinAlg.BlasInt diff --git a/test/linalg/lq.jl b/test/linalg/lq.jl index 7371e47e55d80..0f6fd3fcd163c 100644 --- a/test/linalg/lq.jl +++ b/test/linalg/lq.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, mul!, Adjoint, Transpose diff --git a/test/linalg/matmul.jl b/test/linalg/matmul.jl index 1a019db76a7af..f153eae6f75a7 100644 --- a/test/linalg/matmul.jl +++ b/test/linalg/matmul.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: mul!, Adjoint, Transpose diff --git a/test/linalg/pinv.jl b/test/linalg/pinv.jl index 2c20e9f54bb12..d628f3a75b9cd 100644 --- a/test/linalg/pinv.jl +++ b/test/linalg/pinv.jl @@ -4,7 +4,7 @@ # Test the pseudo-inverse # -using Test +using Test, Random srand(12345) diff --git a/test/linalg/qr.jl b/test/linalg/qr.jl index 3a4611481a994..67349912825a9 100644 --- a/test/linalg/qr.jl +++ b/test/linalg/qr.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted, mul!, Adjoint, Transpose diff --git a/test/linalg/rowvector.jl b/test/linalg/rowvector.jl index 96a9915a1be49..b4289955d2f69 100644 --- a/test/linalg/rowvector.jl +++ b/test/linalg/rowvector.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @testset "Core" begin v = [1,2,3] z = [1+im,2,3] diff --git a/test/linalg/schur.jl b/test/linalg/schur.jl index 34980cad97ebc..99e00d75dd9f9 100644 --- a/test/linalg/schur.jl +++ b/test/linalg/schur.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted diff --git a/test/linalg/special.jl b/test/linalg/special.jl index 9df77f616c9d0..72df9121305ab 100644 --- a/test/linalg/special.jl +++ b/test/linalg/special.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: mul!, Adjoint, Transpose diff --git a/test/linalg/svd.jl b/test/linalg/svd.jl index 28e1b8d4159a3..06294f815bdda 100644 --- a/test/linalg/svd.jl +++ b/test/linalg/svd.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted diff --git a/test/linalg/symmetric.jl b/test/linalg/symmetric.jl index 4737084f621e7..3dd092e7ea62c 100644 --- a/test/linalg/symmetric.jl +++ b/test/linalg/symmetric.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random srand(101) diff --git a/test/linalg/triangular.jl b/test/linalg/triangular.jl index 3655883fd3b8e..354b8ac4c9c6c 100644 --- a/test/linalg/triangular.jl +++ b/test/linalg/triangular.jl @@ -1,7 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license debug = false -using Test +using Test, Random using Base.LinAlg: BlasFloat, errorbounds, full!, naivesub!, transpose!, UnitUpperTriangular, UnitLowerTriangular, mul!, rdiv!, Adjoint, Transpose diff --git a/test/linalg/tridiag.jl b/test/linalg/tridiag.jl index 7d9adea08ed93..e53a938909679 100644 --- a/test/linalg/tridiag.jl +++ b/test/linalg/tridiag.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + #Test equivalence of eigenvectors/singular vectors taking into account possible phase (sign) differences function test_approx_eq_vecs(a::StridedVecOrMat{S}, b::StridedVecOrMat{T}, error=nothing) where {S<:Real,T<:Real} n = size(a, 1) diff --git a/test/linalg/uniformscaling.jl b/test/linalg/uniformscaling.jl index 2f5460893debe..e5669ab637b70 100644 --- a/test/linalg/uniformscaling.jl +++ b/test/linalg/uniformscaling.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random srand(123) diff --git a/test/math.jl b/test/math.jl index 2ddcc9f61531b..da03de06de9c1 100644 --- a/test/math.jl +++ b/test/math.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + function isnan_type(::Type{T}, x) where T isa(x, T) && isnan(x) end diff --git a/test/misc.jl b/test/misc.jl index 8ee89c78102ee..895fcf5999861 100644 --- a/test/misc.jl +++ b/test/misc.jl @@ -2,6 +2,8 @@ # Tests that do not really go anywhere else +using Random + # The following tests for deprecated functionality are disabled when --depwarn=error. # TODO: Clean this up by reimplementing depwarn=error with a logger. if Base.JLOptions().depwarn != 2 diff --git a/test/nullable.jl b/test/nullable.jl index 2edc67cdc3cae..4e1580661a4e3 100644 --- a/test/nullable.jl +++ b/test/nullable.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # "is a null with type T", curried on 2nd argument isnull_oftype(x::Nullable, T::Type) = eltype(x) == T && isnull(x) isnull_oftype(T::Type) = x -> isnull_oftype(x, T) diff --git a/test/numbers.jl b/test/numbers.jl index 083fd6c19e65b..797cdf6ab4887 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -1,6 +1,8 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base.MathConstants +using Random + const ≣ = isequal # convenient for comparing NaNs # remove these tests and re-enable the same ones in the diff --git a/test/offsetarray.jl b/test/offsetarray.jl index 09943ef91ae14..c2effb8bec91c 100644 --- a/test/offsetarray.jl +++ b/test/offsetarray.jl @@ -3,6 +3,7 @@ isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) using Main.TestHelpers.OAs using DelimitedFiles +using Random const OAs_name = join(fullname(OAs), ".") diff --git a/test/operators.jl b/test/operators.jl index 9a883c588d43e..cd4411cde8ed0 100644 --- a/test/operators.jl +++ b/test/operators.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random: randstring + @test ifelse(true, 1, 2) == 1 @test ifelse(false, 1, 2) == 2 diff --git a/test/perf/perfutil.jl b/test/perf/perfutil.jl index e28f7f0fbb8c0..889db90afae4c 100644 --- a/test/perf/perfutil.jl +++ b/test/perf/perfutil.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + const mintrials = 5 const mintime = 2000.0 print_output = isempty(ARGS) diff --git a/test/perf/simd/sum_reduce.jl b/test/perf/simd/sum_reduce.jl index 9ad02e7c9fb7a..b6bf05dbebc54 100644 --- a/test/perf/simd/sum_reduce.jl +++ b/test/perf/simd/sum_reduce.jl @@ -23,4 +23,3 @@ for t in [Float32,Float64] bits = 8*sizeof(t) @timeit(flog_sum_reduce(100,x), "sum_reduction_$bits", "SIMD sum reduction over array of type $t", "SIMD") end - diff --git a/test/pkg.jl b/test/pkg.jl index 624ed28f62d47..e93e009be4f61 100644 --- a/test/pkg.jl +++ b/test/pkg.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license import Base.Pkg.PkgError +using Random: randstring function capture_stdout(f::Function) let fname = tempname() diff --git a/test/ranges.jl b/test/ranges.jl index 75eca6ad821fa..82e46f1354a04 100644 --- a/test/ranges.jl +++ b/test/ranges.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Dates +using Dates, Random # Compare precision in a manner sensitive to subnormals, which lose # precision compared to widening. diff --git a/test/read.jl b/test/read.jl index c72ac33deb9b4..a3ad8a6ae4d4a 100644 --- a/test/read.jl +++ b/test/read.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using DelimitedFiles +using Random mktempdir() do dir diff --git a/test/reduce.jl b/test/reduce.jl index 50bd4ac693e43..38f01f9f11d09 100644 --- a/test/reduce.jl +++ b/test/reduce.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # fold(l|r) & mapfold(l|r) @test foldl(+, Int64[]) === Int64(0) # In reference to issues #7465/#20144 (PR #20160) @test foldl(+, Int16[]) === Int16(0) # In reference to issues #21536 diff --git a/test/reducedim.jl b/test/reducedim.jl index 6bbd491db2b87..11120cc84b2a4 100644 --- a/test/reducedim.jl +++ b/test/reducedim.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # main tests function safe_mapslices(op, A, region) diff --git a/test/reflection.jl b/test/reflection.jl index d471f005db531..cd70ab656b313 100644 --- a/test/reflection.jl +++ b/test/reflection.jl @@ -5,7 +5,7 @@ # sufficient to catch segfault bugs. module ReflectionTest -using Test +using Test, Random function test_ast_reflection(freflect, f, types) @test !isempty(freflect(f, types)) diff --git a/test/repl.jl b/test/repl.jl index 2d15195a37d21..7195a16431015 100644 --- a/test/repl.jl +++ b/test/repl.jl @@ -7,6 +7,7 @@ include("testenv.jl") isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) using Main.TestHelpers import Base: REPL, LineEdit +using Random function fake_repl(f; options::REPL.Options=REPL.Options(confirm_exit=false)) # Use pipes so we can easily do blocking reads diff --git a/test/replcompletions.jl b/test/replcompletions.jl index a941a417aeff2..9268d862b59cd 100644 --- a/test/replcompletions.jl +++ b/test/replcompletions.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base.REPLCompletions +using Random let ex = quote module CompletionFoo @@ -51,7 +52,7 @@ let ex = quote test5(x::Float64) = pass const a=x->x test6()=[a, a] - test7() = rand() > 0.5 ? 1 : 1.0 + test7() = rand(Bool) ? 1 : 1.0 test8() = Any[1][1] kwtest(; x=1, y=2, w...) = pass diff --git a/test/replutil.jl b/test/replutil.jl index dbf15cd9dc659..7340dd9afb514 100644 --- a/test/replutil.jl +++ b/test/replutil.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # For curmod_* include("testenv.jl") diff --git a/test/serialize.jl b/test/serialize.jl index 770654007e41f..2b8f658bf444f 100644 --- a/test/serialize.jl +++ b/test/serialize.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random # Check that serializer hasn't gone out-of-frame @test Serializer.sertag(Symbol) == 1 diff --git a/test/socket.jl b/test/socket.jl index 99a6ebcffcc3a..7a7f2b4628543 100644 --- a/test/socket.jl +++ b/test/socket.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @testset "parsing" begin @test ip"127.0.0.1" == IPv4(127,0,0,1) @test ip"192.0" == IPv4(192,0,0,0) diff --git a/test/sorting.jl b/test/sorting.jl index 9626c5de9e9b1..7afa4e51eb027 100644 --- a/test/sorting.jl +++ b/test/sorting.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base.Order: Forward +using Random @test sort([2,3,1]) == [1,2,3] @test sort([2,3,1], rev=true) == [3,2,1] diff --git a/test/sparse/higherorderfns.jl b/test/sparse/higherorderfns.jl index e4dd960636ef6..20c2904899d8b 100644 --- a/test/sparse/higherorderfns.jl +++ b/test/sparse/higherorderfns.jl @@ -4,6 +4,8 @@ # base/sparse/higherorderfns.jl, particularly map[!]/broadcast[!] for SparseVectors and # SparseMatrixCSCs at present. +using Random + @testset "map[!] implementation specialized for a single (input) sparse vector/matrix" begin N, M = 10, 12 for shapeA in ((N,), (N, M)) diff --git a/test/sparse/sparse.jl b/test/sparse/sparse.jl index c3b32de0c8bc5..07646acd89c46 100644 --- a/test/sparse/sparse.jl +++ b/test/sparse/sparse.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base.LinAlg: mul!, ldiv!, rdiv!, Adjoint, Transpose +using Random @testset "issparse" begin @test issparse(sparse(ones(5,5))) diff --git a/test/sparse/sparsevector.jl b/test/sparse/sparsevector.jl index be73dd551d482..ec46d41b23755 100644 --- a/test/sparse/sparsevector.jl +++ b/test/sparse/sparsevector.jl @@ -1,6 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license using Base.LinAlg: mul!, ldiv!, Adjoint, Transpose +using Random ### Data diff --git a/test/spawn.jl b/test/spawn.jl index 93703cef90c44..709d5f67ebad9 100644 --- a/test/spawn.jl +++ b/test/spawn.jl @@ -4,6 +4,8 @@ # Cross Platform tests for spawn. # ################################### +using Random + valgrind_off = ccall(:jl_running_on_valgrind, Cint, ()) == 0 yescmd = `yes` @@ -520,4 +522,3 @@ let p = spawn(`$sleepcmd 100`) # Should not throw if already dead kill(p) end - diff --git a/test/staged.jl b/test/staged.jl index 29ef1cbe64fb0..2455d36c2fbed 100644 --- a/test/staged.jl +++ b/test/staged.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @generated function staged_t1(a,b) if a == Int return :(a+b) diff --git a/test/statistics.jl b/test/statistics.jl index 84d3ea0616ee7..d4476cd1b6357 100644 --- a/test/statistics.jl +++ b/test/statistics.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random @testset "middle" begin @test middle(3) === 3.0 diff --git a/test/strings/basic.jl b/test/strings/basic.jl index 13031d956f703..db3821a319827 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + @testset "constructors" begin @test String([0x61,0x62,0x63,0x21]) == "abc!" @test String("abc!") == "abc!" diff --git a/test/subarray.jl b/test/subarray.jl index cf9bf9af8d919..c6e1be13ce367 100644 --- a/test/subarray.jl +++ b/test/subarray.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random ######## Utilities ########### diff --git a/test/syntax.jl b/test/syntax.jl index 365fbe7e4682b..42b09fedbeaca 100644 --- a/test/syntax.jl +++ b/test/syntax.jl @@ -2,6 +2,8 @@ # tests for parser and syntax lowering +using Random + import Base.Meta.ParseError function parseall(str) diff --git a/test/testdefs.jl b/test/testdefs.jl index 3191d553cb193..98e5cef6e6ef4 100644 --- a/test/testdefs.jl +++ b/test/testdefs.jl @@ -1,6 +1,6 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license -using Test +using Test, Random function runtests(name, path, isolate=true; seed=nothing) old_print_setting = Test.TESTSET_PRINT_ENABLE[] @@ -14,7 +14,7 @@ function runtests(name, path, isolate=true; seed=nothing) else m = Main end - @eval(m, using Test) + @eval(m, using Test, Random) ex = quote @timed @testset $"$name" begin # srand(nothing) will fail diff --git a/test/version.jl b/test/version.jl index f1e94fd0df477..fe38624f442f2 100644 --- a/test/version.jl +++ b/test/version.jl @@ -1,5 +1,7 @@ # This file is a part of Julia. License is MIT: https://julialang.org/license +using Random + # parsing tests @test v"2" == VersionNumber(2) @test v"3.2" == VersionNumber(3, 2)