Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

simplifying julia code for monte carlo #159

Merged
merged 1 commit into from
Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions chapters/monte_carlo/code/julia/monte_carlo.jl
Original file line number Diff line number Diff line change
@@ -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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be return x_pos^2 + y_pos^2 < radius^2 in my opinion. I don't like unnecessary if/else blocks

return true
else
Expand All @@ -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)
2 changes: 1 addition & 1 deletion chapters/monte_carlo/monte_carlo.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}}$$.
Expand Down