Skip to content

Commit ccae31d

Browse files
committed
estimate Pi value using monte carlo simulation
1 parent 1bc888f commit ccae31d

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
This problem was asked by Google.
3+
4+
The area of a circle is defined as πr^2. Estimate π to 3 decimal
5+
places using a Monte Carlo method.
6+
7+
Hint: The basic equation of a circle is x2 + y2 = r2.
8+
9+
please refer: https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/
10+
for the theory
11+
12+
"""
13+
14+
import numpy as np
15+
interval = int(input())
16+
circle_points = 0
17+
square_points = 0
18+
19+
i = 0
20+
while (i < (interval ** 2)):
21+
rand_x = np.random.uniform(-1,1)
22+
rand_y = np.random.uniform(-1,1)
23+
d = np.square(rand_x) + np.square(rand_y)
24+
if d <= 1:
25+
circle_points += 1
26+
square_points += 1
27+
pi = 4 * (np.divide(circle_points,square_points))
28+
i += 1
29+
30+
#final estimation of final Pi value
31+
print (pi)

0 commit comments

Comments
 (0)