In [1]:
using Plots
using Interact
pyplot()
plot!();
[Plots.jl] Initializing backend: pyplot
WARNING: No working GUI backend found for matplotlib.
In [2]:
"""
Generate a plot illustrating a Monte Carlo evaluation of the integral 
\$\$\int_{\text{xmin}^{\text{xmax}} f(x) \, dx \$\$
using \$N\$ samples.
"""
function monte_carlo_figure(f,xmin,xmax,N)
    plot(f,xmin,xmax,fill=(0,:auto),)
    x = (xmax-xmin)*rand(N)+xmin
    v = (xmax-xmin)*(map(f,x) |> sum)/N
    bar!(x,map(f,x),bar_width=(xmax-xmin)/N)
    plot!(legend=false, xlim=(xmin,xmax))
end
monte_carlo_figure(x->x^2,0,1,1)
Out[2]:
In [3]:
@manipulate for N=1:50
    monte_carlo_figure(x->x^2,0,1,N)
end
Out[3]:
In [12]:
@manipulate for N=5:5:250
    monte_carlo_figure(x->(sin(5x)^2+1)*(sin(5x)^2 <= 0.5),0,2pi,N)
end
Out[12]: