Write a Matlab function that uses the Monte Carlo approach to approximating "pi" using the relative areas of a square and an inscribed circle. I have code but I am not sure how to change it to monte carlo
Afficher commentaires plus anciens
r = 1; % the circle radius
nodp = 1:5; % Number of Decimal Places (NODP) for Pi
i=1; % Counter for number of decimal places
estimates = zeros(1,5); % Estimation for each NODP
steps = zeros(1,5); % Number of steps for each Pi estimation
while i<= length(nodp)
n=0; % No. of points in unit circle
N = 0; % No. of Steps counter/ Points in unit square
flag =0; % Flag for exit condition
while flag == 0
%Generating random points inside unit square
x = rand();
y = rand();
if ((x^2+y^2)<=r^2)
n = n+1; % Successful event for estimating Pi
end
N = N + 1;
estimate = (4*n)/(N);
% Setting appropriate floating point length to store estimate
estimaten = vpa(estimate);
% Counting number of decimal places
d=0;
while (floor(estimaten*10^d)~=estimaten*10^d)
d=d+1;
end
if d == nodp(i) % Required decimal precision achieved
flag = 1; % exit condition set TRUE
estimates(i) = vpa(estimaten); % storing estimate
steps(i) = N; % storing steps
i = i+1; % Next NODP
end
end
end
estimates = estimates.';
nodp = nodp.';
steps = steps.';
format long g
estimates;
T = table(nodp, estimates, steps);
T
1 commentaire
Walter Roberson
le 26 Oct 2017
That code is already Monte Carlo.
Réponses (0)
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!