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 次查看(过去 30 天)
显示 更早的评论
I need to count the points that fall outside and inside and not stop till the number outside reach a specified number
1 个评论
John Chilleri
2017-4-24
编辑:John Chilleri
2017-4-24
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!
回答(1 个)
Image Analyst
2017-4-24
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Monte-Carlo 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!