Skip to content

Commit

Permalink
bugfixes in Libc.rand for Windows (#32895)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevengj authored and JeffBezanson committed Sep 4, 2019
1 parent 921b4f8 commit 5a496c0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
12 changes: 9 additions & 3 deletions base/libc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -382,9 +382,15 @@ Interface to the C `rand()` function. If `T` is provided, generate a value of ty
by composing two calls to `rand()`. `T` can be `UInt32` or `Float64`.
"""
rand() = ccall(:rand, Cint, ())
# RAND_MAX at least 2^15-1 in theory, but we assume 2^16-1 (in practice, it's 2^31-1)
rand(::Type{UInt32}) = ((rand() % UInt32) << 16) (rand() % UInt32)
rand(::Type{Float64}) = rand(UInt32) / 2^32
@static if Sys.iswindows()
# Windows RAND_MAX is 2^15-1
rand(::Type{UInt32}) = ((rand() % UInt32) << 17) ((rand() % UInt32) << 8) (rand() % UInt32)
else
# RAND_MAX is at least 2^15-1 in theory, but we assume 2^16-1
# on non-Windows systems (in practice, it's 2^31-1)
rand(::Type{UInt32}) = ((rand() % UInt32) << 16) (rand() % UInt32)
end
rand(::Type{Float64}) = rand(UInt32) * 2.0^-32

"""
srand([seed])
Expand Down
7 changes: 7 additions & 0 deletions test/misc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,13 @@ end
@test sort([a, b]) == [b, a]
end

@testset "Libc.rand" begin
low, high = extrema(Libc.rand(Float64) for i=1:10^4)
# these fail with probability 2^(-10^4) ≈ 5e-3011
@test 0 low < 0.5
@test 0.5 < high < 1
end

# Pointer 0-arg constructor
@test Ptr{Cvoid}() == C_NULL

Expand Down

0 comments on commit 5a496c0

Please sign in to comment.