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

RFC support for rand(Ranges) and rand(Ranges,dims) #5059

Merged
merged 1 commit into from
Dec 12, 2013
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
11 changes: 9 additions & 2 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ rand(::Type{Float16}) = float16(rand())

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


rand(r::MersenneTwister) = dsfmt_genrand_close_open(r.state)

## random integers
Expand Down Expand Up @@ -181,12 +182,18 @@ function rand(r::Range1{Int128})
ulen = convert(Uint128, length(r))
convert(Int128, first(r) + randu(ulen))
end
function rand{T<:Real}(r::Ranges{T})
ulen = convert(Uint64, length(r)) #length of Ranges is stored as Int, Uint64 is always enough
convert(T, first(r) + randu(ulen)*step(r))
end


# fallback for other integer types
# fallback for other Real types
rand{T<:Integer}(r::Range1{T}) = convert(T, rand(int(r)))
rand{T<:Real}(r::Ranges{T}, dims::Dims) = rand!(r, Array(T, dims))
rand{T<:Real}(r::Ranges{T}, dims::Int...) = rand(r, dims)

function rand!{T<:Integer}(r::Range1{T}, A::Array{T})
function rand!{T<:Real}(r::Ranges{T}, A::Array{T})
for i=1:length(A)
A[i] = rand(r)
end
Expand Down
7 changes: 6 additions & 1 deletion test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
@test minimum([rand(int32(1):int32(7^7)) for i = 1:100000]) > 0
@test(typeof(rand(false:true)) == Bool)

for T in (Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Int128, Uint128, Char, BigInt)
for T in (Int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64, Int128, Uint128, Char, BigInt,
Float16, Float32, Float64, Rational{Int})
r = rand(convert(T, 97):convert(T, 122))
@test typeof(r) == T
@test 97 <= r <= 122
r = rand(convert(T, 97):convert(T,2):convert(T, 122),2)[1]
@test typeof(r) == T
@test 97 <= r <= 122
@test mod(r,2)==1
end

if sizeof(Int32) < sizeof(Int)
Expand Down