Advertisement
frgmsonly

Monte Carlo Pi

Feb 5th, 2016
657
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.02 KB | None | 0 0
  1. clear
  2. clc
  3. tic
  4. format long
  5.  
  6. k = round([exp(3:0.05:15)]);
  7.  
  8. %Use for better Pi estimation:
  9. %k = [10:10:1000 1000:500:100000 100000:10000:1000000];
  10.  
  11. i = 1;
  12. c = zeros(1,length(k));
  13.  
  14. hold on
  15.  
  16. for f = k
  17.     figure(1);
  18.     clf;
  19.  
  20.     x = rand(1,f);
  21.     y = rand(1,f);
  22.    
  23.    
  24. %     Using a non-random distribution does not return accurate
  25. %     values for pi:
  26. %      [x,y] = meshgrid(0:0.01+10/f:1);  
  27. %      x = x(:);
  28. %      y = y(:);
  29.    
  30.     b = sqrt( x.^2+y.^2) <= 1;
  31.     c(i) = 4*mean(b);
  32.    
  33.    
  34.     clc
  35.     subplot(211);
  36.     axis square
  37.     plot(x(b),y(b),'.r')
  38.     hold on
  39.     plot(x(~b),y(~b),'.g')
  40.     pbaspect([1 1 1])
  41.    
  42.     P = polyfit(k(2:i-1),c(2:i-1),1);
  43.     clc
  44.     yfit = P(1)*k(2:i-1)+P(2);
  45.    
  46.     subplot(212);
  47.     semilogx(k(2:i-1),c(2:i-1),'-b')
  48.     title(['\pi = ' num2str(mean(c(1:i)))])
  49.     hold on
  50.     semilogx(k(2:i-1),yfit,'-r');
  51.     pause(0.00000001)
  52.     pbaspect([1 1 1])
  53.    
  54.     i = i+1;
  55.  
  56. end
  57.  
  58. Pi = mean(c)
  59.  
  60. lin_fit_gradient = P(1)
  61.  
  62. time_elapsed = toc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement