MATLAB: MATLAB: I’m having trouble calculating the probability to estimate pi. Any help is appreciated.

homeworkpiprobabilityrand

The MATLAB command rand produces a uniformly-distributed random number between 0 and 1. For example, the MATLAB commands x = rand; and y = rand; will produce a point randomly located in the unit square: (0<x<1) and (0<y<1). The probability that the randomly-generated point (x, y) will lie within the "unit quarter-circle" is equal to the ratio between the area of the unit quarter-circle and that of a unit square; i.e., π/4. Note that (x, y) lies within the unit quarter circle if x^2+y^2<1 Write a MATLAB program that will achieve the following tasks. a. Generate a minimum of 10,000 points (x,y). b. Test each point and increment a counter if x^2+y^2<1. c. Produce an estimate of π. d. Calculate the relative percent true error, E sub t.
n=10000;
for counter=0:n
x= rand;
y=rand;
z=hypot(x,y);
if (z<1)
Est_pi= Area*4;
counter= counter+1;
Error= (((abs(pi-(Est_pi)))/(pi)).*100);
end
end

Best Answer

You have made a decent start. Issues with your code:
1) You use counter for two separate conflicting things. One is the loop counter, and another is the number of "hits" within the unit quarter circle. Use two different variables. E.g., keep the loop counter and have another variable called hits ... set hits = 0 at the start and then inside the loop have hits = hits + 1.
2) Move all of your Est_pi stuff out of the loop and put it after the loop is finished. The estimated probability is simply hits/n. Then apply your formula for the estimate of pi.
3) Change the loop indexing to start at 1 instead of 0.