Skip to content

Commit

Permalink
Random: add a global RANDOM_DEVICE generator
Browse files Browse the repository at this point in the history
Creating a RandomDevice object is cheap but it opens a file
on unix systems, so one can't call `rand(RandomDevice())`
repeatedly too quicly (e.g. in a loop). It can therefore be
convenient to have a readily available generator.
  • Loading branch information
rfourquet committed Jul 5, 2018
1 parent 429e2d5 commit 70e4656
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions stdlib/Random/src/RNGs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ RandomDevice
RandomDevice(::Nothing) = RandomDevice()
srand(rng::RandomDevice) = rng

const RANDOM_DEVICE = RandomDevice()

## MersenneTwister

Expand Down
10 changes: 9 additions & 1 deletion stdlib/Random/src/Random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export srand,
shuffle, shuffle!,
randperm, randperm!,
randcycle, randcycle!,
AbstractRNG, MersenneTwister, RandomDevice,
AbstractRNG, MersenneTwister, RandomDevice, RANDOM_DEVICE,
randjump


Expand Down Expand Up @@ -244,6 +244,14 @@ rand( ::Type{X}, d::Integer, dims::Integer...) where {X} = rand(X
function __init__()
try
srand()
if !Sys.iswindows()
# open /dev/urandom "in-place" (in RANDOM_DEVICE.file)
RANDOM_DEVICE.file.handle = pointer(RANDOM_DEVICE.file.ios)
systemerror("opening file /dev/urandom",
ccall(:ios_file, Ptr{Cvoid},
(Ptr{UInt8}, Cstring, Cint, Cint, Cint, Cint),
RANDOM_DEVICE.file.ios, "/dev/urandom", 1, 0, 0, 0) == C_NULL)
end
catch ex
Base.showerror_nostdio(ex,
"WARNING: Error during initialization of module Random")
Expand Down
4 changes: 4 additions & 0 deletions stdlib/Random/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -677,3 +677,7 @@ end
@test eltype(Random.UInt52(UInt128)) == UInt128
@test eltype(Random.UInt104()) == UInt128
end

@testset "RANDOM_DEVICE" begin
@test rand(Random.RANDOM_DEVICE) isa Float64
end

0 comments on commit 70e4656

Please sign in to comment.