Skip to content
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
23 changes: 13 additions & 10 deletions chapters/monte_carlo/code/julia/monte_carlo.jl
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion chapters/monte_carlo/monte_carlo.md
Original file line number Diff line number Diff line change
Expand Up @@ -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" %}
Expand Down