In: Advanced Math
MATLAB CODE
% Write a matlab program that determines the value of pi using
the monte carlo
% technique. do this for a loop of multiple fixed points. (i.e
100-10000) Plot the
% computed value of pi and the difference from the true value as
this number
% increases. Time the execution of your code for various numbers of
points, and plot
% the precision vs the computational cost.
n = 1;
pimc = zeros(1,1);
exection_time = zeros(1,1);
for nTrial = 100:50:10000
tic
nHit = 0;
r = 1;
for i = 1:nTrial
x = r*rand();
y = r*rand();
if x^2 + y^2 <= (r)^2
nHit = nHit + 1;
end
end
pimc(n) = 4*nHit/nTrial;
exection_time(n) = toc;
n = n + 1;
end
figure(1)
plot(100:50:10000, pimc, 'LineWidth', 2);
xlabel('Number of trials', 'FontSize', 20)
ylabel('Monte carlo estimate of pi', 'FontSize', 20)
print -dpng figure1.png
figure(2)
plot(100:50:10000, pimc-pi, 'LineWidth', 2);
xlabel('Number of trials', 'FontSize', 20)
ylabel('pimc - pi', 'FontSize', 20)
print -dpng figure2.png
figure(3)
plot(exection_time, -log10(abs(pimc-pi)), 'LineWidth', 2);
xlabel('Execution time (s)', 'FontSize', 20)
ylabel('Precision', 'FontSize', 20)
print -dpng figure3.png