Skip to content

Commit

Permalink
Fix #8257
Browse files Browse the repository at this point in the history
This version of `rand(r::Range)` and `rand!(r::Range,a::AbstractArray)`
uses getindex instead of trying to calculate the exact value of the
range. This is good because we avoid duplicating the getindex logic in
`FloatRange`

Also added tests, and fixed a small issue in `in(v, r::Range)` where two
calls to step() is not needed
  • Loading branch information
ivarne committed Sep 10, 2014
1 parent a6c688d commit 48f27bc
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 14 deletions.
18 changes: 5 additions & 13 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ function rand{T<:Integer, U<:Unsigned}(g::RandIntGen{T,U})
end

rand{T<:Union(Signed,Unsigned,Bool,Char)}(r::UnitRange{T}) = rand(RandIntGen(r))
rand{T}(r::Range{T}) = convert(T, first(r) + rand(0:(length(r)-1)) * step(r))
rand{T}(r::Range{T}) = r[rand(1:(length(r)))]

function rand!(g::RandIntGen, A::AbstractArray)
for i = 1 : length(A)
Expand All @@ -218,18 +218,10 @@ end

rand!{T<:Union(Signed,Unsigned,Bool,Char)}(r::UnitRange{T}, A::AbstractArray) = rand!(RandIntGen(r), A)

function rand!{T}(r::Range{T}, A::AbstractArray)
g = RandIntGen(0:(length(r)-1))
f = first(r)
s = step(r)
if s == 1
for i = 1 : length(A)
@inbounds A[i] = convert(T, f + rand(g))
end
else
for i = 1 : length(A)
@inbounds A[i] = convert(T, f + rand(g) * s)
end
function rand!(r::Range, A::AbstractArray)
g = RandIntGen(1:(length(r)))
for i = 1 : length(A)
@inbounds A[i] = r[rand(g)]
end
return A
end
Expand Down
2 changes: 1 addition & 1 deletion base/range.jl
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@ function map!(f::Callable, dest, r::Range)
end

function in(x, r::Range)
n = step(r) == zero(step(r)) ? 1 : iround((x-first(r))/step(r))+1
n = step(r) == 0 ? 1 : iround((x-first(r))/step(r))+1
n >= 1 && n <= length(r) && r[n] == x
end

Expand Down
6 changes: 6 additions & 0 deletions test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,9 @@ a = uuid4()
@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-446655440000")
@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-44665544000098")
@test_throws ArgumentError UUID("z50e8400-e29b-41d4-a716-446655440000")

#issue 8257
i8257 = 1:1/3:100
for i = 1:100
@test rand(i8257) in i8257
end

0 comments on commit 48f27bc

Please sign in to comment.