Skip to content

Commit 128d10f

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`
1 parent 916f965 commit 128d10f

File tree

1 file changed

+4
-12
lines changed

1 file changed

+4
-12
lines changed

base/random.jl

+4-12
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)
@@ -219,17 +219,9 @@ end
219219
rand!{T<:Union(Signed,Unsigned,Bool,Char)}(r::UnitRange{T}, A::AbstractArray) = rand!(RandIntGen(r), A)
220220

221221
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
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

0 commit comments

Comments
 (0)