from
Montecarlo simulation
by Clement Bernard
estimation of pi, using montecarlo method
|
| monte_carlo.m |
%the value of ? can be approximated using a Monte Carlo method
%Draw a square of area 1 on the ground, then inscribe a circle within it.
%Now, scatter some small objects (for example, grains of rice or sand) throughout the square.
%If the objects are scattered uniformly, then the proportion of objects within the circle vs objects within the square should be approximately ?/4,
%which is the ratio of the circle's area to the square's area.
%Thus, if we count the number of objects in the circle, multiply by four,
%and divide by the number of objects in the square, we get an approximation to pi.
n = input('n :');
A = rand(1,n);
B = rand(1,n);
C = A.^2 + B.^2 ;
e=find(C<1);
p = numel(e);
PI = 4.*(p./n)
plot(A,B,'.');
hold on
axis([-1 1 -1 1])
theta = 0:.1:2.*pi;
X = cos(theta);
Y = sin(theta);
plot(X,Y,'y')
pi=pi
disp('the relative deviation ')
dev = (sqrt((PI - pi).^2)/pi).*100
|
|
Contact us at files@mathworks.com