xxxxxxxxxx
1
1
using Statistics
SampleAvg
xxxxxxxxxx
4
1
Base. mutable struct SampleAvg
2
t::Int = 0
3
avg::Float64 = 0.0
4
end
xxxxxxxxxx
5
1
function (s::SampleAvg)(x)
2
s.t += 1
3
s.avg += (x - s.avg) / s.t
4
s.avg
5
end
run_once (generic function with 1 method)
xxxxxxxxxx
12
1
function run_once(b)
2
rms = Float64[]
3
distribution = randn(b)
4
expectation = mean(distribution)
5
sample_avg = SampleAvg()
6
7
for i in 1:2*b
8
avg = sample_avg(distribution[rand(1:b)])
9
push!(rms, abs(avg - expectation))
10
end
11
rms
12
end
xxxxxxxxxx
1
1
using Plots
xxxxxxxxxx
12
1
begin
2
n_runs = 1000
3
p = plot(legend=:topright)
4
5
for b in [2, 10, 100, 1000]
6
rms = mean(run_once(b) for _ in 1:n_runs)
7
xs = (1:2*b) ./ b
8
plot!(p, xs, rms, label="b=$b")
9
end
10
11
p
12
end