Advertisement
Guest User

Untitled

a guest
Feb 5th, 2025
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.71 KB | None | 0 0
  1. n_rep = 10; n_mc = 100000; l_box = 2; r_circ = 0.5; % set values
  2.  
  3. pi_ave = monte_carlo_pi_rep(n_rep, n = n_mc, l = 2);
  4.  
  5. disp("Using " + num2str(n_rep) + " Monte Carlo sims, with " + num2str(n_mc) +...
  6.     " points per sim, and a box size length " + num2str(l_box) +...
  7.     " And a circle, radius " + num2str(r_circ) + newline +...
  8.      " we estimate pi to be "+ num2str(pi_ave));
  9.  
  10. function pi_ave = monte_carlo_pi_rep(n_rep, NameValuePair)
  11. arguments
  12.     n_rep (1,1) double
  13.     NameValuePair.n = 10000;
  14.    
  15.     % these only get passed onto monte_carlo_pi, not needed here
  16.     % using InputParser, we could call "allow unmatched" and these didn't
  17.     % have to be defined in the calling function, could still pass along.
  18.     % In this example, it's simple, but if monte_carlo_pi took a lot of
  19.     % arguments, it would be a hassle (and you have to keep both functions
  20.     % synced). The class method works, but you cannot use the arguments
  21.     % block to assign default values
  22.     NameValuePair.r;
  23.     NameValuePair.l;
  24. end
  25. n = NameValuePair.n;
  26. % since this variable isn't used in monte_carlo_pi, it has to be removed
  27. % before being passed along.
  28. NameValuePair = rmfield(NameValuePair, 'n');
  29. NameValuePair = namedargs2cell(NameValuePair);
  30. pi_ave = 0;
  31. for ii = 1:n_rep
  32.     pi_ave = pi_ave + monte_carlo_pi(n, NameValuePair{:});
  33. end
  34.  
  35. pi_ave = pi_ave/n_rep;
  36. end
  37.  
  38. function pi = monte_carlo_pi(n, NameValuePair)
  39. arguments
  40.     n (1,1) double
  41.     NameValuePair.r = 1;
  42.     NameValuePair.l = 2;
  43. end
  44.  
  45. r_circ = NameValuePair.r;
  46. l_box = NameValuePair.l;
  47.  
  48. p = [-l_box/2,-l_box/2] + l_box*rand(n,2);
  49. r = vecnorm(p, 2, 2);
  50.  
  51. in_circ = r <= r_circ;
  52. area_circ = sum(in_circ)*l_box^2/n;
  53. pi = area_circ/r_circ^2;
  54. end
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement