[Math] Estimate $\pi$ using the Monte Carlo Method in MATLAB

MATLABmonte carlonumerical methods

Evaluate the area of a circle of radius $1= \pi$ using Monte Carlo method . Hence we can generate pairs of random numbers $(x_i,y_i) \in [-1,1]$.

Thus :

$$ \pi= \frac {Number Of Samples Inside The Circle}{Total Number Of Samples} X 4 $$

enter image description here

Consider a unit circle inscribed in a square, each of the small circles drawn on this figure represents a random point that was generated in the square, the red and blue circles represent points inside and outside the unit circle respectively (I got the figure from google) . If we choose a point uniformaly at random within the square, then the probability that the point lies in the unit circle is

$$ \pi= \frac {Number Of Samples Inside The Circle}{Total Number Of Samples} $$

We know that the area of the circumscribed square is $4$, if we knew $p$, then we could compute the area of the unit circle:

Area of the unit circle = $p$ x area of the circumscribed square = $4p$

How to Estimate $\pi$ using the Monte Carlo Method in MATLAB, then what's the error a quarter of a circle ?

Best Answer

The following code is vectorized, and thus typically faster than using loops:

N = 1e6;                % Number of samples
r = 1;                  % Circle radius
x = 2*rand(1,N)-1;      % N samples between -1 and 1
y = 2*rand(1,N)-1;      % N samples between -1 and 1
r2 = x.^2 + y.^2;       % compute squared distance to origin
area = mean(r2<=r^2)*4; % the area is 4 (area of square) times the proportion
                        % of points in the circle. Note that the threshold
                        % should be r^2 (1^2)
error = pi - area       % error in the estimation of pi

N_all = round(10.^(1:.5:7));      % Numbers of samples
r = 1;                            % Circle radius
errors = NaN(size(N_all));        % Preallocate result
for k = 1:numel(N_all)            % Loop over size of N_all
    N = N_all(k);                 % Current N
    x = 2*rand(1,N)-1;            % N samples between -1 and 1
    y = 2*rand(1,N)-1;            % N samples between -1 and 1
    r2 = x.^2 + y.^2;             % compute squared distance to origin
    area = mean(r2<=r^2)*4;       % the area is 4 (area of square) times the
                                  % proportion of points in the circle
    error_all(k) = pi-area;       % error in the estimation of pi
end                               % End loop
semilogx(N_all, error_all, 'o-'); % Plot with logarithmic x axis
grid                              % Use grid

enter image description here

Related Question