Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- n_rep = 10; n_mc = 100000; l_box = 2; r_circ = 0.5; % set values
- pi_ave = monte_carlo_pi_rep(n_rep, n = n_mc, l = 2);
- disp("Using " + num2str(n_rep) + " Monte Carlo sims, with " + num2str(n_mc) +...
- " points per sim, and a box size length " + num2str(l_box) +...
- " And a circle, radius " + num2str(r_circ) + newline +...
- " we estimate pi to be "+ num2str(pi_ave));
- function pi_ave = monte_carlo_pi_rep(n_rep, NameValuePair)
- arguments
- n_rep (1,1) double
- NameValuePair.n = 10000;
- % these only get passed onto monte_carlo_pi, not needed here
- % using InputParser, we could call "allow unmatched" and these didn't
- % have to be defined in the calling function, could still pass along.
- % In this example, it's simple, but if monte_carlo_pi took a lot of
- % arguments, it would be a hassle (and you have to keep both functions
- % synced). The class method works, but you cannot use the arguments
- % block to assign default values
- NameValuePair.r;
- NameValuePair.l;
- end
- n = NameValuePair.n;
- % since this variable isn't used in monte_carlo_pi, it has to be removed
- % before being passed along.
- NameValuePair = rmfield(NameValuePair, 'n');
- NameValuePair = namedargs2cell(NameValuePair);
- pi_ave = 0;
- for ii = 1:n_rep
- pi_ave = pi_ave + monte_carlo_pi(n, NameValuePair{:});
- end
- pi_ave = pi_ave/n_rep;
- end
- function pi = monte_carlo_pi(n, NameValuePair)
- arguments
- n (1,1) double
- NameValuePair.r = 1;
- NameValuePair.l = 2;
- end
- r_circ = NameValuePair.r;
- l_box = NameValuePair.l;
- p = [-l_box/2,-l_box/2] + l_box*rand(n,2);
- r = vecnorm(p, 2, 2);
- in_circ = r <= r_circ;
- area_circ = sum(in_circ)*l_box^2/n;
- pi = area_circ/r_circ^2;
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement