フィルターのクリア

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 Center および File ExchangeTransmitters and Receivers についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by