Skip to content

Instantly share code, notes, and snippets.

@abap34
Last active August 20, 2024 09:22
Show Gist options
  • Save abap34/a5ee20f9caf045c83cef36b0ae112da4 to your computer and use it in GitHub Desktop.
Save abap34/a5ee20f9caf045c83cef36b0ae112da4 to your computer and use it in GitHub Desktop.
julia> function monte_carlo_pi(n)
p = plot(size=(400, 400), legend=false, xlims=(0, 1), ylims=(0, 1), aspect_ratio=:equal)
points = Vector{Tuple{Float64, Float64}}(undef, n)
is_inside = zeros(Bool, n)
for i in 1:n
x, y = rand(), rand()
if x^2 + y^2 < 1
is_inside[i] = true
end
points[i] = (x, y)
end
inner_points = points[is_inside]
outer_points = points[.!is_inside]
scatter!(inner_points, label="Inside")
scatter!(outer_points, label="Outside", shape=:square)
plot!(x -> sqrt(1 - x^2), 0, 1, label="Circle", color=:red)
inside_count = sum(is_inside)
π̋ = 4 * inside_count / n
title!(L"\hat{\pi} = %$π̋")
end
monte_carlo_pi (generic function with 1 method)
julia> monte_carlo_pi(300)
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment