Skip to content

Commit

Permalink
fix buggy rand(RandomDevice(), Bool) (#35590)
Browse files Browse the repository at this point in the history
(cherry picked from commit 0bab06f)
  • Loading branch information
rfourquet authored and KristofferC committed May 10, 2020
1 parent 9651235 commit e76bf14
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions stdlib/Random/src/RNGs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ else # !windows
end

rand(rd::RandomDevice, sp::SamplerBoolBitInteger) = read(getfile(rd), sp[])
rand(rd::RandomDevice, ::SamplerType{Bool}) = read(getfile(rd), UInt8) % Bool

function getfile(rd::RandomDevice)
devrandom = rd.unlimited ? DEV_URANDOM : DEV_RANDOM
Expand Down
32 changes: 32 additions & 0 deletions stdlib/Random/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,38 @@ for rng in [MersenneTwister(), RandomDevice()],
end
end

@testset "rand(Bool) uniform distribution" begin
for n in [rand(1:8), rand(9:16), rand(17:64)]
a = zeros(Bool, n)
as = zeros(Int, n)
# we will test statistical properties for each position of a,
# but also for 3 linear combinations of positions (for the array version)
lcs = unique!.([rand(1:n, 2), rand(1:n, 3), rand(1:n, 5)])
aslcs = zeros(Int, 3)
for rng = (MersenneTwister(), RandomDevice())
for scalar = [false, true]
fill!(a, 0)
fill!(as, 0)
fill!(aslcs, 0)
for _ = 1:49
if scalar
for i in eachindex(as)
as[i] += rand(rng, Bool)
end
else
as .+= rand!(rng, a)
aslcs .+= [xor(getindex.(Ref(a), lcs[i])...) for i in 1:3]
end
end
@test all(x -> 7 <= x <= 42, as) # for each x, fails with proba ≈ 2/35_000_000
if !scalar
@test all(x -> 7 <= x <= 42, aslcs)
end
end
end
end
end

# test reproducility of methods
let mta = MersenneTwister(42), mtb = MersenneTwister(42)

Expand Down

0 comments on commit e76bf14

Please sign in to comment.