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
조회 수: 2 (최근 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!