File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
contents/monte_carlo_integration/code/python Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ import math
2+ import random
3+
4+
5+ def in_circle (x , y , radius = 1 ):
6+ """Return True if the point is in the circle and False otherwise."""
7+ return (x * x + y * y ) < radius * radius
8+
9+ def monte_carlo (n_samples , radius = 1 ):
10+ """Return the estimate of pi using the monte carlo algorithm."""
11+ in_circle_count = 0
12+ for i in range (n_samples ):
13+
14+ # Sample x, y from the uniform distribution
15+ x = random .uniform (0 , radius )
16+ y = random .uniform (0 , radius )
17+
18+ # Count the number of points inside the circle
19+ if (in_circle (x , y , radius )):
20+ in_circle_count += 1
21+
22+ # Since we've generated points in upper left quadrant ([0,radius], [0, radius])
23+ # We need to multiply the number of points by 4
24+ pi_estimate = 4 * in_circle_count / (n_samples )
25+
26+ return pi_estimate
27+
28+ if __name__ == '__main__' :
29+
30+ pi_estimate = monte_carlo (100000 )
31+ percent_error = 100 * abs (math .pi - pi_estimate )/ math .pi
32+
33+ print ("The estimate of pi is: {:.3f}" .format (pi_estimate ))
34+ print ("The percent error is: {:.3f}" .format (percent_error ))
35+
You can’t perform that action at this time.
0 commit comments