Asked by jose sanchez
on 27 Jan 2016

Write a function called mypi which consumes a number that specifies the required accuracy and approximates the value of pi to that accuracy. Use the following algorithm to approximate pi:

Think about a quarter circle inside of a unit square (quarter circle has area pi/4). Pick a random point inside the square. If it is in the quarter circle, you get a "hit", otherwise it's a "miss". The approximate area of the quarter circle will be given by the number of "hits" divided by the number of points chosen.

The function should repeat the process of counting hits and misses until at least 10,000 tries have been made or pi is within the required accuracy. It should return the the estimate for pi.

Answer by Ingrid
on 27 Jan 2016

Edited by Ingrid
on 27 Jan 2016

Accepted Answer

The most important mistake is adding i to hit in the loop instead of just one, i is a counter that goes from 1 to 10000 so it gets really big.

Also, you need to do the error checking with the for loop to allow for preliminary exit after the required precision has been reached.

Finally, be careful with correct naming of your variables. It matters if you write hit or hits and it is not clear were you define hits and it should definitely not be used in calculating the estimated pi as there you want to use the actual number stored in hit

The code below should work as you wanted

maxIt = 10000;

hit= 0;

for i = 1:maxIt

x = rand();

y = rand();

if x^2 + y^2 <= 1

hit = hit + 1 ;

end

piest = 4 * (hit/i);

error = abs(pi-(piest));

if error < .001

sprintf('Number of iterations = %1.0f',i)

break

end

end

disp(piest)

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 5 Comments

## Ingrid (view profile)

Direct link to this comment:https://au.mathworks.com/matlabcentral/answers/265420-i-m-new-to-matlab-i-m-having-trouble-with-this-one#comment_338349

## jose sanchez (view profile)

Direct link to this comment:https://au.mathworks.com/matlabcentral/answers/265420-i-m-new-to-matlab-i-m-having-trouble-with-this-one#comment_338352

## Stephen Cobeldick (view profile)

Direct link to this comment:https://au.mathworks.com/matlabcentral/answers/265420-i-m-new-to-matlab-i-m-having-trouble-with-this-one#comment_338363

## Ingrid (view profile)

Direct link to this comment:https://au.mathworks.com/matlabcentral/answers/265420-i-m-new-to-matlab-i-m-having-trouble-with-this-one#comment_338364

## Stephen Cobeldick (view profile)

Direct link to this comment:https://au.mathworks.com/matlabcentral/answers/265420-i-m-new-to-matlab-i-m-having-trouble-with-this-one#comment_338368

Sign in to comment.