Borrar filtros
Borrar filtros

The approximation error of Monte-Carlo method

4 visualizaciones (últimos 30 días)
Mingxuan
Mingxuan el 10 de Nov. de 2022
Respondida: Image Analyst el 10 de Nov. de 2022
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.

Respuesta aceptada

Image Analyst
Image Analyst el 10 de Nov. de 2022
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

Más respuestas (0)

Categorías

Más información sobre Transmitters and Receivers en Help Center y File Exchange.

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by