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

bugfixes in Libc.rand for Windows #32895

Merged
merged 2 commits into from
Sep 4, 2019
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
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ldexp?

Copy link
Member Author

@stevengj stevengj Aug 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@code_native g(UInt32(3)) reports an enormous amount of code for g(x) = ldexp(Float64(x), -32) for some reason…

(ldexp(x, n) only currently supports floating-point x.)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think ldexp is probably slower here here because it doesn't seem to constant-propagate the exponent?


"""
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 @@ -733,5 +733,12 @@ 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