1.4 ms
1.3 ms
1.1 ms
f (generic function with 1 method)
42.8 μs
7.1 μs
4.7 ms
19.1 μs
udist
Distributions.Uniform{Float64}(a=0.0, b=1.0)
5.4 μs
1.1060069030617743
9.0 μs
1.0142308549286678
180 μs

Approximating the expected value of the Beta distribution

E[x]=p(x)p(x)xdx


where xp(x)=Beta(α1,α2)

Step 1: we identify h(x)=x
Step 2: the function g(x) is simply the probability density function p(x) due the expression for p(x) above:

p(x)=p(x)p(x)dx=p(x)

Step 3 we can use Julia to easily draw N independent sample p(x) using the function Beta. And finally
Step 4 we approximate the expectation with the expression

EBeta(α1,α2)1Nixi

38.7 μs
15.4 ms
expectMC
0.1667417098821608
65.6 μs
expectAnalytic
0.16666666666666666
99.0 ns

Monte Carlo Approximation for Optimization

Monte Carlo Approximation can also be used to solve optimization problems of the form:

x^=argmaxx(a,b)g(x)

if g(x) fulfills the same criteria described above (namely that it is a scaled version of a probability distribution), then (as above) we can define the probability function

p(x)=g(x)C

This allows us to instead solve problem

x^=argmaxxCp(x)

if we can sample form p(x), the solution x^ is easily found by drawing samples from p(x) and determining the location of the samples that has the highest density (Note that the solution is not dependent of the value of C). The following example demonstrates Monte Carlo optimization:

26.9 μs

Example: Monte Carlo Optimization of g(x)=e(x4)22

Say we would like to find the value of xopt which optimizes the function g(x)=e(x4)22. In other words we want to solve the problem

xopt=argmaxxe(x4)22

We could solve for xopt using standard calculus methods, but a clever trick is to use Monte Carlo approximation to solve the problem. First, notice that g(x) is a scaled version of a Normal distribution with mean equal to 4 and unit variance:

g(x)=C×12πe(x4)22

=C×N(4,1)

where C=2π. This means we can solve for xopt by drawing samples from the normal distribution and determining where those samples have the highest density. The following chunck of Julia code solves the optimization problem in this way

15.7 μs
g₃ (generic function with 1 method)
49.4 μs
1.5 ms
35.3 ms
9.9 ms