Monte-Carlo Method
(Difference between revisions)
(dicking with better code.) |
m |
||
Line 10: | Line 10: | ||
% Monte-carlo simulator for solving area of a quarter-circle of radius 1, | % Monte-carlo simulator for solving area of a quarter-circle of radius 1, | ||
% dictated by bounds of x^2+y^2 = 1 | % dictated by bounds of x^2+y^2 = 1 | ||
− | + | ||
% Set up arrays and other constants | % Set up arrays and other constants | ||
x = 0; % x coordinate | x = 0; % x coordinate | ||
Line 16: | Line 16: | ||
total = 10000; % amount of points to generate | total = 10000; % amount of points to generate | ||
count = 0; % number of points inside area | count = 0; % number of points inside area | ||
− | + | ||
% monte-carlo solver | % monte-carlo solver | ||
for i = 1:total | for i = 1:total | ||
Line 27: | Line 27: | ||
end | end | ||
end | end | ||
− | + | ||
% calculate 'true' area and monte-carlo solved area | % calculate 'true' area and monte-carlo solved area | ||
circlearea = pi*1^2; % 'true' area | circlearea = pi*1^2; % 'true' area |
Revision as of 22:03, 21 August 2008
This is a small, simple example of utilising the Monte-Carlo method to calculate the value of pi. It's easy because it is only a 2-dimensional problem and thus is easy to visualise, and is trivial in its code implementation.
Picture the graph shown in the parent article - that of a quarter circle plotted on a unit x-y graph:
Below is a small example piece of Matlab code that does the above simulation:
Code:
% Monte-carlo simulator for solving area of a quarter-circle of radius 1, % dictated by bounds of x^2+y^2 = 1 % Set up arrays and other constants x = 0; % x coordinate y = 0; % y coordinate total = 10000; % amount of points to generate count = 0; % number of points inside area % monte-carlo solver for i = 1:total % generate a random point in 0<x<1 and 0<y<1 x = rand; % random number between 0 and 1 y = rand; % monte-carlo check if inside bounds if (x^2+y^2 <= 1) count = count + 1; end end % calculate 'true' area and monte-carlo solved area circlearea = pi*1^2; % 'true' area montearea = count/total*4; % monte-carlo area
This, when run on my computer, produced the result of 0.783. The area of a quarter circle works out to be π/4 if the radius is 1. π/4 = 0.7854, so you can see that this is quite close. More iterations than 1000 would produce a closer answer.