Skip to content

Commit

Permalink
Add missing rand(::AbstractRNG, ::Type{Char}) method
Browse files Browse the repository at this point in the history
use simple rejection sampling over valid codepoint range
  • Loading branch information
jakebolewski committed May 6, 2015
1 parent 58c16b6 commit 5986e58
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
13 changes: 12 additions & 1 deletion base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,21 @@ end
rand(r::MersenneTwister, ::Type{Int64}) = reinterpret(Int64, rand(r, UInt64))
rand(r::MersenneTwister, ::Type{Int128}) = reinterpret(Int128, rand(r, UInt128))

## random complex values
## random Complex values

rand{T<:Real}(r::AbstractRNG, ::Type{Complex{T}}) = complex(rand(r, T), rand(r, T))

# random Char values
# use simple rejection sampling over valid Char codepoint range
function rand(r::AbstractRNG, ::Type{Char})
while true
c = rand(0x00000000:0x0010fffd)
if is_valid_char(c)
return reinterpret(Char,c)
end
end
end

## Arrays of random numbers

rand(r::AbstractRNG, dims::Dims) = rand(r, Float64, dims)
Expand Down
6 changes: 3 additions & 3 deletions test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ srand(0); rand(); x = rand(384);
@test -10 <= rand(-10:-5) <= -5
@test -10 <= rand(-10:5) <= 5
@test minimum([rand(Int32(1):Int32(7^7)) for i = 1:100000]) > 0
@test(typeof(rand(false:true)) == Bool)

@test(typeof(rand(false:true)) === Bool)
@test(typeof(rand(Char)) === Char)
@test length(randn(4, 5)) == 20
@test length(bitrand(4, 5)) == 20

Expand Down Expand Up @@ -292,7 +292,7 @@ for rng in ([], [MersenneTwister()], [RandomDevice()])
rand!(rng..., BitArray(5)) ::BitArray{1}
rand!(rng..., BitArray(2, 3)) ::BitArray{2}

for T in [Base.IntTypes..., Bool, Float16, Float32, Float64]
for T in [Base.IntTypes..., Bool, Char, Float16, Float32, Float64]
a0 = rand(rng..., T) ::T
a1 = rand(rng..., T, 5) ::Vector{T}
a2 = rand(rng..., T, 2, 3) ::Array{T, 2}
Expand Down

0 comments on commit 5986e58

Please sign in to comment.