# Seven Lines of Julia (examples sought)

**URL:** <https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416>\
**Category:** General Usage\
**Created:** [November 19, 2020, 7:37am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416 "2020-11-19T07:37:29Z")\
**Posts on this page:** 1\
**Showing post:** 26

<div class="post-metadata">

**Author:** ![mschauer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mschauer/32/13946_2.png) [@mschauer](https://discourse.julialang.org/u/mschauer)\
**Post date:** [November 23, 2020, 9:47am UTC](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416/26 "2020-11-23T09:47:32Z")

</div>

Agree with Tamas, but it is also nice to have a couple of very short examples. Here a Gibbs sampler sampling the posterior parameters of normal observations with mean distributed a priori as N(μ0, σ0) and precision 1/σ^2 a priori as Gamma(α, β):

```julia
using Distributions, Statistics
function mc(x, iterations, μ0 = 0., τ0 = 1e-7, α = 0.0001, β = 0.0001)
    sumx, n = sum(x), length(x)
    μ, τ = sumx/n, 1/var(x)
    samples = [(μ, τ)]
    for i in 1:iterations
        μ = rand(Normal((τ0*μ0 + τ*sumx)/(τ0 + n*τ), 1/sqrt(τ0 + n*τ)))
        τ = rand(Gamma(α + n/2, 1/(β + 0.5*sum((xᵢ-μ)^2 for xᵢ in x))))
        push!(samples, (μ, τ))
    end
    samples
end

```

Usage

```julia
samples = mc(rand(Normal(0.2, 1.7^(-0.5)), 1_000), 10_000)
μs, τs = first.(samples), last.(samples)
println("mean μ = ", mean(μs), " ± ", std(μs))
println("precision τ = ", mean(τs), " ± ", std(τs))

```

Output:

> `mean μ = 0.2076960556449643 ± 0.023693641548604788`  
> `precision τ = 1.8301418451485263 ± 0.08225999887566306`

---

_[View the full topic](https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416)._
