Estimating pi using for and while loop for specific tolerance.

조회 수: 9 (최근 30일)
Eric
Eric 2020년 4월 8일
댓글: Rik 2020년 4월 15일
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
Rik
Rik 2020년 4월 15일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

David Hill
David Hill 2020년 4월 8일
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

카테고리

Help CenterFile Exchange에서 Monte-Carlo에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by