Improving metropolis-hastings code

A like to use handwritten MH at times, it reads so nicely in Julia

using Distributions
using Random

function logtar(x)
    if x < 0
        return -Inf
    else
        return -x
    end
end

x = [3.0]
for i in 2:100000
    currentx = x[end]
    proposedx = currentx + rand(Normal(0,1))   
    l = logtar(proposedx) - logtar(currentx)
    if -randexp() < l
        currentx = proposedx
    end
    push!(x,currentx)
end 

mean(x), var(x)
mean(Exponential()), var(Exponential())
5 Likes