diff --git a/chapters/monte_carlo/code/julia/monte_carlo.jl b/chapters/monte_carlo/code/julia/monte_carlo.jl index 818d60efb..fee58cdcd 100644 --- a/chapters/monte_carlo/code/julia/monte_carlo.jl +++ b/chapters/monte_carlo/code/julia/monte_carlo.jl @@ -1,27 +1,30 @@ # function to determine whether an x, y point is in the unit circle -function in_circle(x_pos::Float64, y_pos::Float64, radius::Float64) - if (x_pos^2 + y_pos^2 < radius^2) - return true - else - return false - end +function in_circle(x_pos::Float64, y_pos::Float64) + + # Setting radius to 1 for unit circle + radius = 1 + return x_pos^2 + y_pos^2 < radius^2 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 c819457eb..382ec9924 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -38,7 +38,7 @@ each point is tested to see whether it's in the circle or not: {% method %} {% sample lang="jl" %} -[import:2-8, lang:"julia"](code/julia/monte_carlo.jl) +[import:2-7, lang:"julia"](code/julia/monte_carlo.jl) {% sample lang="c" %} [import:7-9, lang:"c_cpp"](code/c/monte_carlo.c) {% sample lang="hs" %}