Skip to content

Commit 7edddb0

Browse files
committed
Fix #8257
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 Backport of 48f27bc PR: #8273
1 parent e91de92 commit 7edddb0

File tree

3 files changed

+12
-14
lines changed

3 files changed

+12
-14
lines changed

base/random.jl

+5-13
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ function rand{T<:Integer, U<:Unsigned}(g::RandIntGen{T,U})
207207
end
208208

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

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

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

221-
function rand!{T}(r::Range{T}, A::AbstractArray)
222-
g = RandIntGen(0:(length(r)-1))
223-
f = first(r)
224-
s = step(r)
225-
if s == 1
226-
for i = 1 : length(A)
227-
@inbounds A[i] = convert(T, f + rand(g))
228-
end
229-
else
230-
for i = 1 : length(A)
231-
@inbounds A[i] = convert(T, f + rand(g) * s)
232-
end
221+
function rand!(r::Range, A::AbstractArray)
222+
g = RandIntGen(1:(length(r)))
223+
for i = 1 : length(A)
224+
@inbounds A[i] = r[rand(g)]
233225
end
234226
return A
235227
end

base/range.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ function map!(f::Callable, dest, r::Range)
560560
end
561561

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

test/random.jl

+6
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,9 @@ a = uuid4()
165165
@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-446655440000")
166166
@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-44665544000098")
167167
@test_throws ArgumentError UUID("z50e8400-e29b-41d4-a716-446655440000")
168+
169+
#issue 8257
170+
i8257 = 1:1/3:100
171+
for i = 1:100
172+
@test rand(i8257) in i8257
173+
end

0 commit comments

Comments
 (0)