Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix buggy rand(RandomDevice(), Bool) #35590

Merged
merged 1 commit into from
Apr 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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