Skip to content

Commit f263f02

Browse files
committed
MCMC function
1 parent d50e599 commit f263f02

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

Project.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "NumericalAlgorithms"
22
uuid = "3b47cccd-2e0f-43d2-aaa1-0b61cbee3591"
33
authors = ["Murat Koptur <[email protected]>"]
4-
version = "0.1.5"
4+
version = "0.1.6"
55

66
[deps]
77
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"

src/MCMC.jl

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
include("Random.jl")
2+
3+
function MCMC(f::Function, count::UInt64, burnInPer::UInt64)
4+
x = zeros(count + burnInPer)
5+
x[1] = 1.0
6+
7+
for i = 2:(count + burnInPer)
8+
currx = x[i - 1]
9+
# TODO: Replace randn and rand with my own implementation
10+
propx = currx + randn(1)[1]
11+
a = f(propx) / f(currx)
12+
if (rand() < a)
13+
x[i] = propx
14+
else
15+
x[i] = currx
16+
end
17+
end
18+
19+
return x[(burnInPer+1):end]
20+
end

src/NumericalAlgorithms.jl

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ module NumericalAlgorithms
1212
include("Constants.jl")
1313
include("Differentiation.jl")
1414
include("Integration.jl")
15+
include("MCMC.jl")
1516
include("Random.jl")
1617
include("RootFinding.jl")
1718
include("StatisticalTests.jl")
@@ -25,5 +26,6 @@ export Dual
2526
export CalcSingleIntegral, CalcDoubleIntegral, CalcMonteCarloIntegral
2627
export LFG, RANMAR, vanderCorputSeq, haltonSeq, faureSeq, sobolSeq
2728
export RunsTest
29+
export MCMC
2830

2931
end # module

test/runtests.jl

+8
Original file line numberDiff line numberDiff line change
@@ -155,4 +155,12 @@ end
155155
z2 = RunsTest(rndnums_rng2)
156156
z2 = round(z2, digits=2)
157157
@test -2.58 < z1 < 2.58
158+
end
159+
160+
@testset "Markov Chain Monte Carlo" begin
161+
f(x::Float64)::Float64 = x < 0 ? 0 : exp(-x)
162+
a::UInt64 = 10000
163+
b::UInt64 = 2500
164+
res = MCMC(f, a, b)
165+
@test length(res) == a
158166
end

0 commit comments

Comments
 (0)