Wednesday, January 23, 2013

Monte Carlo Simulation of Pi with MATLAB

Using Monte Carlo simulation, the value of π can be approximated as (1/n) * Σ(4*sqrt(1-U_i^2)), where n is a large number representing the number of simulation trials, and U_i represents the i-th trial result from a uniform distribution in [0,1], for 1 ≤ i ≤ n. The MATLAB codes to run this simulation is quite straightforward:

numTrials = 1000000000;    %number of simulation trials
count = 0;
for trial = 1:numTrials
    roll = rand;    %uniform distribution [0,1]
    count = count + 4*sqrt(1-roll^2);
end
sum(count)/numTrials

In this simulation, n = 1,000,000,000. The output of 3.1416 matches the value of pi in all 4 displayed decimal places.