Sunday, October 2, 2011

Monte Carlo integration: How the number of iterations used affects precision

While it may be obvious that with Monte Carlo integration, the more iterations performed will result in higher precision, it's always fun to look at something graphically. Since I had already written a program that approximated the value of pi (check it out here), I decided to look at how standard deviations change with increasing numbers of iterations.

I chose to run 10 sets of iterations: 2, 4, 8, 32, 64, 128, 256, 512, and 1024. Why these values were chosen becomes obvious in the script, but you can use any set of iterations you want. Each set of iterations was run 10,000 times and standard deviations were calculated from these.
Figure 1: Stdev vs. number of iterations. Note the x-axis is log scale so that the trend can more easily be seen.
Here's my script:

% Graphing standard deviations of pi vs. number of iterations
% using Monte Carlo integration
close all
clear all

for x = 1:10;           
   
y=2^x;
   
for i = 1:10000;
    n = 2*(rand(2,y))- 1;    % generates random numbers between -1 and 1
   
    pts = 0;                  % starting value for total points
    circ = 0;                 % starting value for points within circle
   
    for R = 1:y;
        d = sqrt((n(1,R))^2 + (n(2,R))^2);
        pts = pts + 1;
        if d <= 1;
            circ = circ + 1;
        end  
    end
    Pi(1,i) = (4*circ)/pts;

end

STD(1,x) = std(Pi);
IT(1,x) = y;

end

plot (log10(IT),STD)
title('Standard Deviation vs. Number of Iterations');
xlabel('log10(number of iterations)');
ylabel('Standard deviation');

No comments:

Post a Comment