Filter löschen
Filter löschen

Hello, I wish for someone to help me explain (with a code example) how i can generate a random variable using Monte Carlo simulation.with loop for and if ,Am just a basic user of matlab,I will be grateful to get a response

2 Ansichten (letzte 30 Tage)
Hello, I wish for someone to help me explain (with a code example) how i can generate a random variable using Monte Carlo simulation.with loop for and if ,Am just a basic user of matlab,I will be grateful to get a response

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 31 Aug. 2020
N = 100000;
count = 0;
R = 5;
for K = 1 : N
r = R * rand(1,2);
if sqrt(r(1)^2 + r(2)^2) <= R
count = count + 1;
end
end
pi_approximation = 4 * (count / N);
  4 Kommentare
Walter Roberson
Walter Roberson am 31 Aug. 2020
N = 10000;
hits = 0;
misses = 0;
R = 5;
subplot(1,2,1)
axes equal
h = animatedline('Linestyle', 'none', 'marker', '*');
for K = 1 : N
r = R * rand(1,2);
if sqrt(r(1)^2 + r(2)^2) <= R
hits = hits + 1;
addpoints(h,r(1), r(2));
if mod(count, 25); drawnow; end
else
misses = misses + 1;
end
end
pi_approximation = 4 * (count / N);
subplot(1,2,2)
bar([hits, misses]);
xticks([1 2]);
xticklabels({'hits', 'misses'});

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Monte-Carlo finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by