Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7f9aed8

Browse files
author
Amogh Singhal
authored
Create estimate_pi.py
1 parent d13809e commit 7f9aed8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎estimate_pi.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /