Skip to content

Commit 91aa94f

Browse files
committedSep 30, 2014
factor out common code in rand(::RandIntGen) methods
And simplify method signatures: creation of RandIntGen instances is controlled by `randintgen`, so the type constraints were useless.
1 parent 57bd2b7 commit 91aa94f

File tree

1 file changed

+12
-20
lines changed

1 file changed

+12
-20
lines changed
 

‎base/random.jl

+12-20
Original file line numberDiff line numberDiff line change
@@ -178,31 +178,23 @@ for (T, U) in [(Uint8, Uint32), (Uint16, Uint32),
178178
@eval randintgen(k::$T) = k<1 ? error("range must be non-empty") : RandIntGen($T, convert($U, k))
179179
end
180180

181+
@inline function rand_lessthan{U}(u::U)
182+
while true
183+
x = rand(U)
184+
x <= u && return x
185+
end
186+
end
187+
181188
# this function uses 32 bit entropy for small ranges of length <= typemax(Uint32) + 1
182189
# RandIntGen is responsible for providing the right value of k
183-
function rand{T<:Union(Uint64, Int64)}(g::RandIntGen{T,Uint64})
184-
local x::Uint64
185-
if (g.k - 1) >> 32 == 0
186-
x = rand(Uint32)
187-
while x > g.u
188-
x = rand(Uint32)
189-
end
190-
else
191-
x = rand(Uint64)
192-
while x > g.u
193-
x = rand(Uint64)
194-
end
195-
end
190+
function rand{T}(g::RandIntGen{T,Uint64})
191+
x = (g.k - 1) >> 32 == 0 ?
192+
uint64(rand_lessthan(itrunc(Uint32, g.u))) :
193+
rand_lessthan(g.u)
196194
return reinterpret(T, one(Uint64) + x % g.k)
197195
end
198196

199-
function rand{T<:Integer, U<:Unsigned}(g::RandIntGen{T,U})
200-
x = rand(U)
201-
while x > g.u
202-
x = rand(U)
203-
end
204-
itrunc(T, one(U) + x % g.k)
205-
end
197+
rand{T,U}(g::RandIntGen{T,U}) = itrunc(T, one(U) + rand_lessthan(g.u) % g.k)
206198

207199

208200
## Randomly draw a sample from an AbstractArray r

0 commit comments

Comments
 (0)
Please sign in to comment.