logo

Monte Carlo Method 📂Machine Learning

Monte Carlo Method

Definition

Simply put, the Monte Carlo method is about doing something many times at random.

Description

Although it’s a simple method, there are few methods as easy and certain as trying many times. Of course, “easy” refers to when utilizing a computer. Monte Carlo refers to the name of an area famous for its casinos and hotels in northern Monaco. The name “Monte Carlo method” also comes from the Monte Carlo Casino in Monte Carlo. One famous example of the Monte Carlo method is calculating the value of pi through random sampling.

Calculating Pi

Setup.png

Consider a circle with a radius of $1$ and a square that circumscribes it, with a side length of $2$. The area of the square is $2 \times 2 = 4$, and the area of the circle is $\pi \cdot 1^{2} = \pi$, therefore,

$$ \frac{\pi}{4} = \dfrac{\includegraphics[height=1.5em]{https://freshrimpsushi.com/community/data/editor/2304/2175452097_1682457480.9206.png}}{\includegraphics[height=1.5em]{https://freshrimpsushi.com/community/data/editor/2304/2175452097_1682457480.9073.png}} = \frac{\includegraphics[height=1.5em]{https://freshrimpsushi.com/community/data/editor/2304/2175452097_1682457480.9157.png}}{\includegraphics[height=1.5em]{https://freshrimpsushi.com/community/data/editor/2304/2175452097_1682457481.1163.png}} \implies \pi = 4 \frac{\includegraphics[height=1.5em]{https://freshrimpsushi.com/community/data/editor/2304/2175452097_1682457480.9157.png}}{\includegraphics[height=1.5em]{https://freshrimpsushi.com/community/data/editor/2304/2175452097_1682457481.1163.png}} $$

Thus, by performing random sampling from a uniform distribution within the area of $[0, 1] \times [0, 1]$, multiplying the ratio of points that fall inside the unit circle by $4$ gives an approximate value of $\pi$. Naturally, the more samples that are drawn, the closer it will be to the actual value of $\pi$. Implementing in Julia and actually calculating,

using Distributions

function MC(n)
    x = rand(Uniform(0,1),n)
    y = rand(Uniform(0,1),n)
    z = x.^2 + y.^2
    return 4*sum(z.<=1)/n
end

julia> MC(100)
3.32 

julia> MC(1000)
3.184

julia> MC(10000)
3.1504

julia> MC(100000)
3.1394

See Also