Advertisement
Francoo

(pseudo) Monte Carlo method for Pi v2.0

Aug 25th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.04 KB | None | 0 0
  1. % Despite originally was a "true" Monte Carlo, now it just uses a regular matrix of points, so it can have a better consistency without any randomness.
  2.  
  3. trucnt=0;
  4. totcnt=0;
  5. trucord=[0;0];
  6. falcord=[0;0];
  7.  
  8. stepsize=0.002; %Set here the horizontal/vertical step size
  9. maxval=1; %Set here the maximum value on horizontal/vertical axis
  10.  
  11. for xcord=0:stepsize:maxval;
  12.     for ycord=0:stepsize:maxval
  13.         r=sqrt( ycord ^2 + xcord ^2 );
  14.         if r < maxval
  15.             trucnt=trucnt+1;
  16.             trucord(1:2,end+1)=[xcord;ycord];
  17.         else
  18.             falcord(1:2,end+1)=[xcord;ycord];
  19.         end
  20.         totcnt=totcnt+1;
  21.     end
  22. end
  23.  
  24. %Statistics:
  25. fprintf('Total/True: %u, %u\n', totcnt, trucnt)
  26. fprintf('Ratio: %0.7g%%\n', 100*trucnt/totcnt)
  27. fprintf('Pi: %0.6g\n', 4*trucnt/totcnt)
  28. fprintf('Error: %0.3g%%\n', 100*abs(4*trucnt/totcnt-pi)/pi)
  29.  
  30. %Plotting:
  31. scatter(trucord(1,1:end),trucord(2,1:end),1,'g')
  32. hold on
  33. scatter(falcord(1,1:end),falcord(2,1:end),1,'b')
  34. hold off
  35. axis square
  36. title 'sqrt(x^2+y^2)<1'
  37. xlabel 'x'
  38. ylabel 'y'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement