Skip to content

Commit

Permalink
ENH: use rand instead of draw for drv sampling (#164)
Browse files Browse the repository at this point in the history
* ENH: use rand instead of draw for drv sampling (closes #162)

* Add `rand!(::AbstractArray{<:Integer}, ::DiscreteRV)` method
  • Loading branch information
sglyon authored Jul 13, 2017
1 parent d3a303b commit 05906bf
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
13 changes: 11 additions & 2 deletions src/discrete_rv.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Make a single draw from the discrete distribution
- `out::Int`: One draw from the discrete distribution
"""
draw(d::DiscreteRV) = searchsortedfirst(d.Q, rand())
Base.rand(d::DiscreteRV) = searchsortedfirst(d.Q, rand())

"""
Make multiple draws from the discrete distribution represented by a
Expand All @@ -68,4 +68,13 @@ Make multiple draws from the discrete distribution represented by a
- `out::Vector{Int}`: `k` draws from `d`
"""
draw(d::DiscreteRV, k::Int) = Int[draw(d) for i=1:k]
Base.rand(d::DiscreteRV, k::Int) = Int[rand(d) for i=1:k]

function Base.rand!{T<:Integer}(out::AbstractArray{T}, d::DiscreteRV)
@inbounds for I in eachindex(out)
out[I] = rand(d)
end
out
end

@deprecate draw Base.rand
2 changes: 1 addition & 1 deletion src/markov/mc_tools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ Base.start(mcis::MCIndSimulator) = (mcis.init, 0)

function Base.next(mcis::MCIndSimulator, state::Tuple{Int,Int})
ix, t = state
(ix, (draw(mcis.drvs[ix]), t+1))
(ix, (rand(mcis.drvs[ix]), t+1))
end

Base.done(mcis::MCIndSimulator, s::Tuple{Int,Int}) = s[2] >= mcis.len
Expand Down
15 changes: 13 additions & 2 deletions test/test_discrete_rv.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@testset "Testing discrete_rv.jl" begin

# set up
n = 10
x = rand(n)
Expand All @@ -10,7 +10,18 @@
@test drv.Q[end] 1.0

# test lln
draws = draw(drv, 100000)
draws = rand(drv, 100_000)
c = counter(draws)
counts = Array{Float64}(n)
for i=1:n
counts[i] = c[i]
end
counts ./= sum(counts)

@test isapprox(Base.maximum(abs, counts - drv.q), 0.0; atol=1e-2)

draws = Array{Int}(100_000)
rand!(draws, drv)
c = counter(draws)
counts = Array{Float64}(n)
for i=1:n
Expand Down

0 comments on commit 05906bf

Please sign in to comment.