Estimating pi using for and while loop for specific tolerance.

9 views (last 30 days)
This code I wrote needs tweaking to correctly estimate pi with a specific tolerance but I can't figure out how to get it to work. The question I am attempting involves the Monte Carlo Method and is as follows:
"Think of a quarter circle inside a unit square; then the quarter circle has area pi/4 . You pick a random point inside the square using the Matlab function rand. If it is in the quarter circle, you get a "hit" and if not, you get a "miss". The approximate area of the quarter circle will be given by the number of hits divided by the number of points you chose. Your function should repeat the process of counting hits and misses until at least 10,000 tries have been made and the successive estimates are within the prescribed tolerance. It should return the estimated value of pi as well as the number of tries."
Thanks in advance!
function [estpi,n] = mypi(tol)
%% Task 2: Calculating Pi.
format long
x=0;
y=0;
c=0;
n=10000;
hits=0;
hit=[]; %Initialising the hit matrix.
err=[];
estpi=[];
error=1+tol;%This is were the error scaler is initialised.
for c=1:n
x=rand;
y=rand;
hit(c)=x.^2+y.^2<1;
hits=sum(hit);
while error>tol
estpi(c)=4*hits/c;
c=c+1;
err(c)=abs(estpi(c)-error);
error=err(c);
end
end
end
  1 Comment
Rik
Rik on 15 Apr 2020
In response to your flag ("This is not useful to the community as it is for a homework and so therefore I would like it removed. Thank you."):
We don't generally remove questions that received feedback from others, especially answers. There are also no rules against posting homework-related questions (apart from the rules from your school/university). There is even an entire thread on this topic: here.
If you have compelling reasons to want your question removed anyway, please detail them in a new flag, or contact Mathworks support.

Sign in to comment.

Answers (1)

David Hill
David Hill on 8 Apr 2020
function [estpi,n] = mypi(tol)
error=1;
hits=0;
n=0;
while error>tol
if norm(rand(2,1))<=1
hits=hits+1;
end
n=n+1;
error=abs(pi-4*hits/n);
end
estpi=4*hits/n;
end

Community Treasure Hunt

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

Start Hunting!