using Plots
# two useful defaults: uniform random: 0 to 1.0
# gaussian: -Inf to Inf
N1 = 1800
p1 = histogram(rand(N1), normalize = true, label="rand")
histogram!(randn(N1), normalize = true, alpha=0.5, label="randn")
# sampled distribution
rho1(x) = 3 / 4 * (1 - x^2)
function _dist()
data = zeros(N1)
i1 = 1
while true
x1 = -1 + 2 * rand()
# max. rho(x) is 3/4
y1 = 3/4 * rand()
# von Neumann rejection: accepts points under the line
if y1 < rho1(x1)
data[i1] = x1
i1 += 1
else
end
i1 > N1 && break
end
return data
end
p2 = histogram(_dist(), normalize = true, label="random")
plot!(range(-1, 1, length=20), rho1, label="rho(x)")
figure = plot(p1, p2, layout=(2, 1), size=(650, 650))
sampling an arbitrary distributions $\rho(x)$¶
Direct Sampling¶
from uniform random distribution $r1, r2$, collect y = max(r1, r2) to get $ \rho(y) = 2 y $
Inverse Transform Method¶
construct $r(x) = F(x) = \int^x dx^\prime \, \rho(x^\prime)$ such that
$ dr = dx \, \rho(x) $;
invert to get $x(r)$
e.g. sample $ x(r) = -\lambda \ln r $
to get
$\rho(x) = \frac{1}{\lambda} e^{-\frac{x}{\lambda}}$
Von Neumann Rejection¶
generate a pair of random numbers (x, y)
if y < rho(x), accepts x
such a collection of x satisfies dist. rho(x)
# simple examples of direct and inverse transform methods
Nmax = 1200
dist1 = zeros(Nmax)
for i1 in 1:Nmax
dist1[i1] = max(rand(), rand())
end
p1 = histogram(dist1, normalize=:pdf, alpha = 0.6, label="direct sampling")
plot!(range(0.0, 1.0, length=20), x-> 2*x,
label="2x", color="gray", line=(dash=:dash))
# rejection
function reject(rho; Nx=6500, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0)
i1 = 1
bag = zeros(Nx)
while true
xx = xmin + rand()*(xmax-xmin)
yy = ymin + rand()*(ymax-ymin)
if yy < rho(xx)
bag[i1] = xx
i1 += 1
end
i1 > Nx && break
end
return bag
end
reject (generic function with 1 method)
# random distribution by direct sampling
tau = 1.0
# using knwon result
r2x = r -> -tau *log(1-r)
N = 2500
r_arr = rand(N)
# a new random distribution is just as easy as this:
x_arr = r2x.(r_arr)
x1_arr = reject(x->exp(-x/tau)/tau, xmax=4.0)
histogram(x_arr, normalize=:pdf, alpha = 0.6, label="direct sampling")
plot!(range(0.0, 10.0, length=50), t->exp(-t/tau)/tau, xlim=(0,5), label="analytic")
histogram!(x1_arr, normalize=:pdf, alpha=0.5, label="rejection")
let
rho = x -> 3/4 * (1 - x^3)
data = reject(rho, xmin=-1, xmax=1, ymax=3/2)
# again, improve the integral routine!
xvec = range(-1, 1, 150)
dx = 2.0 / (length(xvec) - 1)
norm = sum([rho(xx+dx/2) * dx for xx in xvec[1:end-1]])
histogram(data, normalize = true, label="rejection", alpha=0.5)
plot!(range(-1, 1, length = 250), x -> rho(x) / norm,
label="analytic", color="gray", line=(dash=:dash))
end
# application
tau = 1.0
r2x = r -> -tau *log(1-r)
N = 2000
r_arr = rand(N)
# as easy as that
x_arr = r2x.(r_arr)
rho = x -> exp(-x/tau)/tau
f = x -> exp(-x^2)
ret1 = sum( @. f(x_arr)/rho(x_arr) )/N
println([ret1, sqrt(pi)/2])
[0.891308913841106, 0.8862269254527579]
# random distribution by direct sampling
r2x = r -> tan(pi *(r-0.4))
N = 2500
r_arr = rand(N)
# as easy as that
x_arr = r2x.(r_arr)
histogram(x_arr, normalize=:pdf, label="direct sampling", alpha=0.5)
plot!(range(-10.0, 10.0, length=2500), x->1/(1+x^2)/pi, xlim=(-10,10),
label="analytic", color="gray", line=(dash=:dash))
Monte Carlo Integration¶
To calculate an integral using Monte Carlo Method:
$$ \cal{I} = \int_{a}^{b} \, dx \, f(x). $$
The simplest way is to consider a uniform distribution x_arr in a:b and compute
$$ \begin{align} \cal{I} &\approx (b-a) \, \langle f(x) \rangle \\ \langle f(x) \rangle &= \frac{1}{N} \, \sum_{\{x_i\}} \, f(x_i) \end{align} $$
The second line makes explicit an alternative way to interpret an integral: via the mean value theorem.
There are two ways to understand this:
- First, an integral is given by a weighed sum:
$$ {\cal{I}} = \sum_i \, w_i f(x_i). $$ Here we have a constant weight: $w_i = \frac{b-a}{N}$.
- Another way to view this is to consider sampling the function with the collection $\{x\}_\rho$, obtained by rejection or direct sampling, such that
$$ d r = dx \, \rho(x). $$ Equivalently $\frac{dr}{dx} = \rho(x),$ and evaluate
$$ {\cal{I}} = \int \, dr \, \frac{f(x)}{\rho(x)} \rightarrow \frac{1}{N} \, {\sum_{\{x_i\}_\rho}} \, \frac{f(x_i)}{\rho(x_i)}. $$ The sum $\sum_{\{x_i\}_\rho}$ means we sample the summand with a collection of random numbers according to $\rho$.
Note that $\rho$ should be properly normalized. In the simplest case,
$$ x = a + (b-a) \times r $$
$$ \rho(x) = 1/(b-a) $$
and we recover the standard result. If not we need to include a factor of
$${\rm norm} = \int dx \, \rho(x) $$ to get the correct result:
$$ {\cal{I}} \approx \frac{\rm norm}{N} \, {\sum_{\{x_i\}_\rho}} \, \frac{f(x_i)}{\rho(x_i)} = {\rm norm} \times \langle \frac{f}{\rho} \rangle_\rho $$
Finally we give yet another interpretation. The sampling of a function with $\{x_i\}_\rho$ can be understood as
$$ \langle {\cal{F}} \rangle_\rho = \frac{1}{N} \, {\sum_{\{x_i\}_\rho}} \, {\cal{F}}(x_i) \rightarrow \frac{\int dx \, \rho(x) \, {\cal{F}}(x)}{\int dx \, \rho(x)} $$ The integral estimate is just a by-product of this sampling. The nice thing is that we can now select a non-uniform distribution to improve the convergence.
"
# application
r2x = r -> tan(pi *(r-0.5))
N = 2500
r_arr = rand(N)
# as easy as that
x_arr = r2x.(r_arr)
rho = x -> 1/(1+x^2)/pi
f = x -> exp(-x^2)
ret1 = sum( @. f(x_arr)/rho(x_arr) ) / N
println([ret1, sqrt(pi)])
[1.7499907899834157, 1.7724538509055159]
Importance Sampling¶
The freedom to choose $\rho(x)$ is the key idea of importance sampling: we can choose $\rho(x)$ which matches the behavior of $f(x)$ to allow efficient evaluation (sampling) of the integral.
As a demonstration, let's compute the integral
$$\begin{align} \cal{I} = \int_0^2 dx \, e^{x^2} \end{align}$$
by sampling a random distribution of $\rho(x) = e^{x}$.
let
using QuadGK
f = x -> exp(x^2)
N = 280
rho = x -> exp(x)
norm = exp(2.0) - 1.0
data = reject(rho; Nx = N,
xmin = 0.0, xmax = 2.0,
ymin=0.0, ymax=exp(2.0))
ret1 = sum([ f(xx)/rho(xx) for xx in data ]) / N * norm
ret2 = sum( f.(2*rand(N)) ) / N * 2.0
compare = quadgk(f, 0.0, 2.0)[1]
[ret1, ret2, compare]
end
3-element Vector{Float64}:
16.302697116826735
18.490868819174874
16.45262776550723
What if we choose ${\cal{F}}(x) = {\rho(x)}^{-1}$ ?¶
$$ \langle \rho^{-1} \rangle_\rho = \frac{\int dx}{\int dx \, \rho(x)} = \frac{b-a}{\rm norm} $$
so we can estimate even the norm with the sampling technique. The self-contained integration formula becomes
$$ \begin{align} {\cal{I}} &= \int dx \, f(x) \\ &= {\rm norm} \times \langle \frac{f}{\rho} \rangle_\rho \\ &= (b-a) \times \left[ \langle {\rho}^{-1} \rangle_\rho \right]^{-1} \times \langle \frac{f}{\rho} \rangle_\rho. \end{align} $$
This construction is called the harmonic mean.
let
using QuadGK
f = x -> exp(x^2)
N = 800
rho = x -> exp(x)
data = reject(rho; Nx = N,
xmin = 0.0, xmax = 2.0,
ymin=0.0, ymax=exp(2.0))
ret = 2
_f1 = x -> f(x)/rho(x)
ret *= sum( @. _f1.(data) ) / N
_f2 = x -> 1/rho(x)
ret /= sum( @. _f2.(data) ) / N
compare = quadgk(f, 0.0, 2.0)[1]
[ret, compare]
end
2-element Vector{Float64}:
15.644191845917092
16.45262776550723