Skip to content

Commit 935ae05

Browse files
committed
Change dir structure and fixed string formating
1 parent 6f9aec3 commit 935ae05

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+

contents/monte_carlo_integration/monte_carlo_integration.md

+4
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ each point is tested to see whether it's in the circle or not:
5959
[import:13-15, lang:"java"](code/java/MonteCarlo.java)
6060
{% sample lang="swift" %}
6161
[import:15-17 lang:"swift"](code/swift/monte_carlo.swift)
62+
{% sample lang="py" %}
63+
[import:5-7 lang:"python"](code/python/monte_carlo.py)
6264
{% endmethod %}
6365

6466
If it's in the circle, we increase an internal count by one, and in the end,
@@ -112,6 +114,8 @@ Feel free to submit your version via pull request, and thanks for reading!
112114
[import, lang:"java"](code/java/MonteCarlo.java)
113115
{% sample lang="swift" %}
114116
[import, lang:"swift"](code/swift/monte_carlo.swift)
117+
{% sample lang="py" %}
118+
[import, lang:"python"](code/python/monte_carlo.py)
115119
{% endmethod %}
116120

117121

0 commit comments

Comments
 (0)