I need to find the area of a circle using the monte carlo method the twist is i need to generate random points until the number that lie outside reach a specified number ie. 4*(#inside/inside+outside)=pi
3 views (last 30 days)
Show older comments
I need to count the points that fall outside and inside and not stop till the number outside reach a specified number
1 Comment
John Chilleri
on 24 Apr 2017
Edited: John Chilleri
on 24 Apr 2017
You can do this using a while loop.
while (4*(in/(in+out)) ~= pi)
% random point
% update in/out appropriately
end
% determine area approximation
Although I imagine continuing till it equals pi could cause problems, I would do something along the lines of:
while (abs(4*(in/(in+out)) - pi) > 1e-6)
% random point
% update in/out appropriately
end
% approximate area
This will instead continue to apply Monte Carlo until your condition is roughly 5 decimal digits accurate to pi.
Hope this helps!
Answers (1)
Image Analyst
on 24 Apr 2017
Try this:
R = 1;
numInside = 0;
numOutside = 0;
maxOutsideCount = 100000; % Whatever you want...
loopCounter = 0;
while numOutside < maxOutsideCount
x = rand;
y = rand;
r = sqrt(x^2+y^2);
if r < R
numInside = numInside + 1;
else
numOutside = numOutside + 1;
end
loopCounter = loopCounter + 1;
end
fprintf('Exited after %d points: %d inside and %d outside.\n', ...
loopCounter, numInside, numOutside);
Adapt as needed.
0 Comments
See Also
Categories
Find more on Monte-Carlo in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!