Skip to content

Commit ea86ca2

Browse files
committed
fixed radius hardcoding issue
1 parent 52b8e5c commit ea86ca2

File tree

2 files changed

+7
-8
lines changed

2 files changed

+7
-8
lines changed

chapters/monte_carlo/code/python/monte_carlo.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,26 @@
22
import random
33

44

5-
def in_circle(x, y):
5+
def in_circle(x, y, radius = 1):
66
"""Return True if the point is in the circle and False otherwise."""
7-
radius = 1.0
87
return (x*x + y*y) < radius*radius
98

10-
def monte_carlo(n_samples):
9+
def monte_carlo(n_samples, radius = 1):
1110
"""Return the estimate of pi using the monte carlo algorithm."""
1211
in_circle_count = 0
1312
for i in range(n_samples):
1413

1514
# Sample x, y from the uniform distribution
16-
x = random.uniform(0,1)
17-
y = random.uniform(0,1)
15+
x = random.uniform(0, radius)
16+
y = random.uniform(0, radius)
1817

1918
# Count the number of points inside the circle
2019
if(in_circle(x, y, radius)):
2120
in_circle_count += 1
2221

23-
# Since we've generated points in upper left quadrant ([0,1], [0,1])
22+
# Since we've generated points in upper left quadrant ([0,radius], [0, radius])
2423
# We need to multiply the number of points by 4
25-
pi_estimate = 4 * in_circle_count / (n_samples * radius * radius)
24+
pi_estimate = 4 * in_circle_count / (n_samples)
2625

2726
return pi_estimate
2827

chapters/monte_carlo/monte_carlo.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ each point is tested to see whether it's in the circle or not:
4848
{% sample lang="d" %}
4949
[import:2-5, lang:"d"](code/d/monte_carlo.d)
5050
{% sample lang="py" %}
51-
[import:5-8, lang:"python"](code/python/monte_carlo.py)
51+
[import:5-7, lang:"python"](code/python/monte_carlo.py)
5252
{% sample lang="go" %}
5353
[import:12-14, lang:"golang"](code/go/monteCarlo.go)
5454
{% endmethod %}

0 commit comments

Comments
 (0)