The approximation error of Monte-Carlo method
조회 수: 2 (최근 30일)
이전 댓글 표시
Define the in-script function calc_pi(n) which inplements the Monte-Carlo method to approximate pi with n points generated.
the code I have is follows:
function value = calc_pi(n)
x = rand(N,1);
y = rand(N,1);
r = x.^2+y.^2;
inside = r<=1;
outside = r>1;
end
I am not too sure if I got the function right or not for the Monte-Carlo method.
then we need to create row vector N from 1e3 to 1e6 with stepsize 1e3. and use a for loop to create a row vector err such that the i-th element of err(i) is the absolute error to approxiamte pi with N(i) points.
N = [1e3:1e3:1e6];
err = [];
for i = 1:length(N)
err(i) = abs(calc_pi( ? );
end
I'm stuck on what to put after the calc_pi which is in the question mark area.
댓글 수: 0
채택된 답변
Image Analyst
2022년 11월 10일
Here's some fixes. Not done but you can continue with your homework until it's done.
N = 1e3 : 1e3 : 1e6;
err = zeros(length(N), 1);
for k = 1:length(N)
n = N(k);
if rem(k, 50) == 0
fprintf('On iteration %d.\n', k)
end
err(k) = abs(calc_pi(n));
end
plot(err, 'b-', 'LineWidth', 2);
xlabel('n')
ylabel('Error')
grid on;
%============================================================
function value = calc_pi(n)
x = rand(n,1);
y = rand(n,1);
r = x.^2+y.^2;
inside = sum(r <= 1);
outside = r>1;
% TO DO assign value.
value = 20;
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Industrial Statistics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!