Last active
August 20, 2024 09:22
-
-
Save abap34/a5ee20f9caf045c83cef36b0ae112da4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment