compute pi using monte-carol simulation in matlab

Here's a simple code that uses a Monte-Carlo simulation to estimate the value of pi in MATLAB:

main.m
n = 1000;  % number of random points
count = 0; % number of points inside circle

for i=1:n
    x = rand();     % generate random x-coordinate
    y = rand();     % generate random y-coordinate
    dist = sqrt(x^2 + y^2);  % distance from point to origin
    if dist <= 1   % if point inside circle
        count = count + 1;  
    end
end

% calculate estimate of pi
pi_estimate = 4 * count / n
396 chars
15 lines

In this code, we generate n random points in the square with corners (0, 0), (1, 0), (0, 1), and (1, 1), and count the number of points that fall within the unit circle centered at the origin. This count is then used to estimate the value of pi using the formula pi = 4*(number of points inside circle)/(total number of points).

related categories

gistlibby LogSnag