Skip to content

Commit 0bab06f

Browse files
authored
fix buggy rand(RandomDevice(), Bool) (#35590)
1 parent 9a712ae commit 0bab06f

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

stdlib/Random/src/RNGs.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ else # !windows
2525
end
2626

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

2930
function getfile(rd::RandomDevice)
3031
devrandom = rd.unlimited ? DEV_URANDOM : DEV_RANDOM

stdlib/Random/test/runtests.jl

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,38 @@ for rng in [MersenneTwister(), RandomDevice()],
455455
end
456456
end
457457

458+
@testset "rand(Bool) uniform distribution" begin
459+
for n in [rand(1:8), rand(9:16), rand(17:64)]
460+
a = zeros(Bool, n)
461+
as = zeros(Int, n)
462+
# we will test statistical properties for each position of a,
463+
# but also for 3 linear combinations of positions (for the array version)
464+
lcs = unique!.([rand(1:n, 2), rand(1:n, 3), rand(1:n, 5)])
465+
aslcs = zeros(Int, 3)
466+
for rng = (MersenneTwister(), RandomDevice())
467+
for scalar = [false, true]
468+
fill!(a, 0)
469+
fill!(as, 0)
470+
fill!(aslcs, 0)
471+
for _ = 1:49
472+
if scalar
473+
for i in eachindex(as)
474+
as[i] += rand(rng, Bool)
475+
end
476+
else
477+
as .+= rand!(rng, a)
478+
aslcs .+= [xor(getindex.(Ref(a), lcs[i])...) for i in 1:3]
479+
end
480+
end
481+
@test all(x -> 7 <= x <= 42, as) # for each x, fails with proba ≈ 2/35_000_000
482+
if !scalar
483+
@test all(x -> 7 <= x <= 42, aslcs)
484+
end
485+
end
486+
end
487+
end
488+
end
489+
458490
# test reproducility of methods
459491
let mta = MersenneTwister(42), mtb = MersenneTwister(42)
460492

0 commit comments

Comments
 (0)