필터 지우기
필터 지우기

The approximation error of Monte-Carlo method

조회 수: 4 (최근 30일)
Mingxuan
Mingxuan 2022년 11월 10일
답변: Image Analyst 2022년 11월 10일
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.

채택된 답변

Image Analyst
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개)

카테고리

Help CenterFile Exchange에서 Transmitters and Receivers에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by