The approximation error of Monte-Carlo method

4 次查看(过去 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.

采纳的回答

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 中查找有关 Industrial Statistics 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by