Skip to content

Commit

Permalink
Merge pull request #5059 from ggggggggg/rand_ranges
Browse files Browse the repository at this point in the history
RFC support for rand(Ranges) and rand(Ranges,dims)
  • Loading branch information
JeffBezanson committed Dec 12, 2013
2 parents c5364db + e8062ee commit af2e4a9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
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

0 comments on commit af2e4a9

Please sign in to comment.