Skip to content
AgileLogics
5 min read

Statistics and Random Numbers

Prerequisites: Linear algebra

The Statistics standard library

using Statistics

xs = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]
println(mean(xs), " ", median(xs))
println(var(xs), " ", std(xs))
println(std(xs, corrected = false))
println(quantile(xs, [0.25, 0.5, 0.75]))
ys = 2 .* xs .+ 1
println(cor(xs, ys), " ", cov(xs, ys))
5.0 4.5
4.571428571428571 2.138089935299395
2.0
[4.0, 4.5, 5.5]
1.0 9.142857142857142

var and std use the sample (n − 1) formula by default; corrected = false gives the population version. For distributions, hypothesis tests, and regression, use the Distributions.jl, HypothesisTests.jl, and GLM.jl packages.

Random numbers

using Random

rng = Xoshiro(42)
println(rand(rng))
println(rand(rng, 1:6, 5))
println(round.(randn(rng, 3), digits = 4))
println(rand(rng, ["red", "green", "blue"]))
println(shuffle(rng, 1:5))
0.6293451231426089
[3, 3, 5, 5, 1]
[-0.9129, 0.6316, 1.4387]
red
[1, 5, 2, 3, 4]
  • rand() gives a float in [0, 1); rand(1:6, 5) five dice rolls; randn normally distributed numbers; rand(collection) a random element.
  • Pass an explicit generator (Xoshiro(seed)) to get reproducible results. The exact numbers for a given seed may change between Julia versions, so don't hard-code them in tests.

Seeding the global generator

using Random

Random.seed!(2024)
a = rand(3)
Random.seed!(2024)
b = rand(3)
println(a == b)
println(all(0 .<= a .< 1))
true
true

Random.seed! resets the default generator — handy at the top of a script or notebook.

A Monte Carlo estimate of π

using Random

function estimate_pi(n, rng)
    inside = 0
    for _ in 1:n
        x, y = rand(rng), rand(rng)
        inside += x^2 + y^2 <= 1
    end
    return 4 * inside / n
end

est = estimate_pi(1_000_000, Xoshiro(1))
println(abs(est - π) < 0.01)
true

inside += condition adds true (1) or false (0).