MATLAB Answers

approximate the value of π using the following algorithm based on geometric probability. This algorithm is an example of the so called monte carlo method

67 views (last 30 days)
Luxsanan Ramanusam
Luxsanan Ramanusam on 6 Apr 2016
Answered: sam0037 on 12 Apr 2016
I have written the code for the estimation of pi but I don't understand ow to put hits and misses in my coding and how to ake the code loop.
Code:
clf
clear all
% MC estimate of pi
n=10000
x=rand([1 n])
y=rand ([1 n])
figure(1)
for i = 1:n
plot(x(i), y(i), 'b+')
hold on
end
% plot(x, y, 'r+')
c=0
s=0
for i=1:n
s=s+1
if x(i)^2 +y(i)^2 <=1 % inside circle
c=c+1
% hold on
else % else outside circle
plot (x(i), y(i), 'r+')
end
end
p=c/s
pi_=p*4

  0 Comments

Sign in to comment.

Accepted Answer

sam0037
sam0037 on 12 Apr 2016
Hi,
The code seems to work fine for computing PI using Hit & Miss Monte Carlo algorithm. In this code the variable 'c' is the number of hits and the variable 's' is the total number of samples i.e. hits + misses.
This code can be optimized further in terms of performance in MATLAB using vectorization. This link mentions how this can be done. However for illustration purpose I have taken the liberty to modify the code as below to show how to compute hits and misses using both vectorization and looping techniques. If this is not what you were looking for then kindly elaborate on the query.
% MC estimate of pi
clear all;
clc;
%%initialize random points
n=10000;
x=rand([1 n]);
y=rand ([1 n]);
%%compute using vectorization
radii = sqrt(x.^2+y.^2);
hits = sum(radii<=1);
misses = n-hits;
pi_mc = 4*(hits/n);
fprintf('\nUsing Vectorization:: HITS = %d, MISSES = %d, PI = %f\n',hits,misses,pi_mc);
%%compute using a loop
c=0;
s=0;
for i=1:n
s=s+1;
if x(i)^2 +y(i)^2 <=1 % inside circle
c=c+1;
end
end
p=c/s;
pi_=p*4;
fprintf('\nUsing Loop:: HITS = %d, MISSES = %d, PI = %f\n',c,s-c,pi_);

  0 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!