MATLAB This problem is another entry in our\" numerical approximation of pi\" se
ID: 3789716 • Letter: M
Question
MATLAB
This problem is another entry in our" numerical approximation of pi" series. Assume that you have created x_0, and y_0; two real random numbers between 0 and 1. If x_0 and y_0 are coordinates of a single point P in the x - y plane, the random point P (x_0, y_0) is confined to a 1-by-l square cornered on the origin (OABC in Figure 1). Recall that r_0 = Squareroot x^2_0 + y^2_0 gives the distance between P and the origin O. We know that the probability of r_0 being less than 1 (i.e. the probability for point P to be confined to circular sector OAC) is equal to the area of the circular sector OAC over the area of the square OABC or pi/4. Write a program to calculate the value of pi from this method by using a for loop for 1000 counts and creating two real random numbers between 0 and 1 for x_0 and y_0. Repeat the problem once more except this time by using a while loop, find out how many times you need to repeat the loop to calculate pi with 10^-9 difference from the exact value defined by MATLAB variable pi. This problem is worth 10 pointsExplanation / Answer
a.
count = 0; %%count counts number of time the value of r is less than 1
for i = 1 : 1000
x = rand;
y = rand;
r = sqrt(x^2 + y^2);
if r <= 1
count = count + 1;
end
end
prob = count / 1000; %%we divide count by 1000 since we already know that loop itterated 1000 times
p = prob * 4; %% we know that prob = pi/4
fprintf ("our estimated pi value is %d ",p);
___________________________________________________________________________
b.
count_less = double(0); %%count_less counts number of time the value of r is less than 1
count_experiment = double(0);%%count_experiment counts number of time experiment is carried out
prob = double(0);
while abs(pi - prob*4) > 10^-9 %%prob is pi/4, so we multiply prob with 4 and then compare
x = rand;
y = rand;
r = sqrt(x^2 + y^2);
count_experiment = count_experiment + 1;
if r <= 1
count_less = count_less + 1;
end
prob = count_less/count_experiment; %probability need to be calculated in every itteration
end;
fprintf ("Itteration required = %d ",count_experiment);
____________________________________________________________________________
Hope that the above code-segment helps you. The code is self-explanatory and very simple
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.