Skip to content

Instantly share code, notes, and snippets.

@carstenbauer
Last active March 21, 2023 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carstenbauer/ff03a29f2b9211b565cc72a007e5fc3a to your computer and use it in GitHub Desktop.
Save carstenbauer/ff03a29f2b9211b565cc72a007e5fc3a to your computer and use it in GitHub Desktop.
Makie Animation Pi
function pi_animation()
N = 1000
Random.seed!(123)
# setup figure
f = Figure(resolution = (1000,400))
dart_fig = f[1,1]
dart_ax = Axis(dart_fig, aspect=1, title="Monte-Carlo-Simulation")
approx_fig = f[1,2]
approx_ax = Axis(approx_fig, title="Quality of Approximation")
xlims!(approx_ax, 1, N)
ylims!(approx_ax, π-1, π+1)
arc!(dart_fig, Point2f(0,0), 1, 0, 2π; strokewidth=3)
text!(N, 3.1, text="π", color="red", align = (:right, :center))
# init data
hits = 0
dist = Uniform(-1,1)
pi_current = Observable(Float64[])
darts = Observable(Point2f[])
colors = Observable(Symbol[])
scatter!(dart_fig, darts, markersize = 4, color = colors)
lines!(approx_fig, pi_current, linewidth=1, color = :black, markersize=1)
hlines!(approx_fig, [π], color=:red, linewidth=2)
# # plot and animate
record(f, "pi-animation.mp4", 1:N) do i
x, y = rand(dist), rand(dist)
darts[] = push!(darts[], Point2f(x,y))
if sqrt(x^2 + y^2) <= 1
hits += 1
colors[] = push!(colors[], :blue)
else
colors[] = push!(colors[], :black)
end
pi_current[] = push!(pi_current[], 4.0*hits/i)
end
return f
end
pi_animation()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment