diff --git a/base/random.jl b/base/random.jl index 6fc336a55e3ad..55a81fe5d11e2 100644 --- a/base/random.jl +++ b/base/random.jl @@ -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 @@ -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 diff --git a/test/random.jl b/test/random.jl index 88443e3d59b31..3d2745df1edb0 100644 --- a/test/random.jl +++ b/test/random.jl @@ -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)