

Matlab Code : Calculating Pi Using Monte Carlo
Hypothesis:
For a circle with radius (r) inscribed in a squared with side length 2r, the ratio of the area of circle/square = Pi/4 Assume there is a square that starts at the origin is of 2cm in side length. If we generate a random number for x coordinate and y coordinate, for this point to be inside the area circle, it must satisfy the equation: x^2 + y^2 < r^2 => No of randomly generated points within the circle/Total Generated Points must be equal to Pi/4 => Approximation of Pi = 4*Points within circle/Total Points Matlab Code: Code:
% Monte Carlo computation of pi. n = input(' Enter n: '); count = 0; for i=1:n, x = 2*rand1; y = 2*rand1; if x^2 + y^2 <= 1, count = count + 1; end; end; pi_approx = 4*(count/n); 
The Following 5 Users Say Thank You to Oxymoron For This Useful Post:  


You can also use parallel computing to speed it up. There is a link on this page for PI calculation using parallel computing and monte carlo:
Monte Carlo Simulation  MATLAB & Simulink 
The Following User Says Thank You to rg123 For This Useful Post:  
Tags 
computational finance, matlab, monte carlo simulation, random number generation 
Thread Tools  
Display Modes  

