diff --git a/chapters/monte_carlo/code/julia/monte_carlo.jl b/chapters/monte_carlo/code/julia/monte_carlo.jl index 818d60efb..efdb9083d 100644 --- a/chapters/monte_carlo/code/julia/monte_carlo.jl +++ b/chapters/monte_carlo/code/julia/monte_carlo.jl @@ -1,5 +1,8 @@ # function to determine whether an x, y point is in the unit circle -function in_circle(x_pos::Float64, y_pos::Float64, radius::Float64) +function in_circle(x_pos::Float64, y_pos::Float64) + + # Setting radius to 1 for unit circle + radius = 1 if (x_pos^2 + y_pos^2 < radius^2) return true else @@ -8,20 +11,24 @@ function in_circle(x_pos::Float64, y_pos::Float64, radius::Float64) end # function to integrate a unit circle to find pi via monte_carlo -function monte_carlo(n::Int64, radius::Float64) +function monte_carlo(n::Int64) pi_count = 0 for i = 1:n point_x = rand() point_y = rand() - if (in_circle(point_x, point_y, radius)) + if (in_circle(point_x, point_y)) pi_count += 1 end end - pi_estimate = 4*pi_count/(n*radius^2) + # This is using a quarter of the unit sphere in a 1x1 box. + # The formula is pi = (box_length^2 / radius^2) * (pi_count / n), but we + # are only using the upper quadrant and the unit circle, so we can use + # 4*pi_count/n instead + pi_estimate = 4*pi_count/n println("Percent error is: ", signif(100*(pi - pi_estimate)/pi, 3), " %") end -monte_carlo(10000000, 0.5) +monte_carlo(10000000) diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index 8b283a3bd..3933dfe15 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -27,7 +27,7 @@ $$ This means, $$ -\text{Area}_{\text{circle}} = \text{Area}_{\text{square}}\times\text{Ratio} = 4r^2 \times \text{ratio} +\text{Area}_{\text{circle}} = \text{Area}_{\text{square}}\times\text{Ratio} = 4r^2 \times \text{Ratio} $$ So, if we can find the $$\text{Ratio}$$ and we know $$r$$, we should be able to easily find the $$\text{Area}_{\text{circle}}$$.