File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ import numpy as np
2+ from math import pi as PI
3+
4+ def estimate_pi (sims = 100 ):
5+ """
6+ takes the number of simulations as input to estimate pi
7+ """
8+
9+ # counter to hold points lying inside the circle
10+ in_circle = 0
11+
12+ for s in range (0 ,sims ):
13+
14+ x = np .random .rand ()
15+ y = np .random .rand ()
16+
17+ if (x ** 2 + y ** 2 ) <= 1 :
18+ in_circle += 1
19+
20+ # The ratio of pts. inside the circle and the total pts. will be same as the ratio
21+ # of the area of circle to the area of the square, inside which the circle is inscribed
22+ # Area of circle = PI * R * R
23+ # Area of square = (2R) * (2R)
24+
25+ pi_estimated = 4.0 * in_circle / sims
26+
27+ print ("Simulations ran: " , sims )
28+ print ("Estimated pi" , pi_estimated )
29+ print ("Error" , PI - pi_estimated )
30+
31+ estimate_pi (sims = 100 )
32+ print ()
33+ estimate_pi (sims = 1000 )
34+ print ()
35+ estimate_pi (sims = 10000 )
36+ print ()
37+ estimate_pi (sims = 100000 )
38+ print ()
39+ estimate_pi (sims = 1000000 )
40+ print ()
41+ estimate_pi (sims = 10000000 )
42+ print ()
43+ estimate_pi (sims = 100000000 )
44+ print ()
45+ estimate_pi (sims = 1000000000 )
You can’t perform that action at this time.
0 commit comments