Skip to content

Commit 0e2dbc5

Browse files
committed
simplifying julia code
1 parent 64a9d0f commit 0e2dbc5

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed
Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# function to determine whether an x, y point is in the unit circle
2-
function in_circle(x_pos::Float64, y_pos::Float64, radius::Float64)
2+
function in_circle(x_pos::Float64, y_pos::Float64)
3+
4+
# Setting radius to 1 for unit circle
5+
radius = 1
36
if (x_pos^2 + y_pos^2 < radius^2)
47
return true
58
else
@@ -8,20 +11,24 @@ function in_circle(x_pos::Float64, y_pos::Float64, radius::Float64)
811
end
912

1013
# function to integrate a unit circle to find pi via monte_carlo
11-
function monte_carlo(n::Int64, radius::Float64)
14+
function monte_carlo(n::Int64)
1215

1316
pi_count = 0
1417
for i = 1:n
1518
point_x = rand()
1619
point_y = rand()
1720

18-
if (in_circle(point_x, point_y, radius))
21+
if (in_circle(point_x, point_y))
1922
pi_count += 1
2023
end
2124
end
2225

23-
pi_estimate = 4*pi_count/(n*radius^2)
26+
# This is using a quarter of the unit sphere in a 1x1 box.
27+
# The formula is pi = (box_length^2 / radius^2) * (pi_count / n), but we
28+
# are only using the upper quadrant and the unit circle, so we can use
29+
# 4*pi_count/n instead
30+
pi_estimate = 4*pi_count/n
2431
println("Percent error is: ", signif(100*(pi - pi_estimate)/pi, 3), " %")
2532
end
2633

27-
monte_carlo(10000000, 0.5)
34+
monte_carlo(10000000)

chapters/monte_carlo/monte_carlo.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ $$
2727
This means,
2828

2929
$$
30-
\text{Area}_{\text{circle}} = \text{Area}_{\text{square}}\times\text{Ratio} = 4r^2 \times \text{ratio}
30+
\text{Area}_{\text{circle}} = \text{Area}_{\text{square}}\times\text{Ratio} = 4r^2 \times \text{Ratio}
3131
$$
3232

3333
So, if we can find the $$\text{Ratio}$$ and we know $$r$$, we should be able to easily find the $$\text{Area}_{\text{circle}}$$.

0 commit comments

Comments
 (0)