In [ ]:
using Gadfly
using Morsel
app = Morsel.app()
get(app, "/") do req, res
#If the n parameter was specified, read it
#e.g. http://localhost:8000/?n=1000
if haskey(req.state, :url_params) && haskey(req.state[:url_params], "n")
n = int(req.state[:url_params]["n"])
println("Read URL parameter n = $n")
else
n=3000
println("Using default parameter n = $n")
end
calculate(n)
"""
<html>
<title>My first Julia app</title>
<body>
<h1>Estimating <em>π</em> using Monte Carlo</h1>
Here is a simple example of estimating the value of <em>π</em>.
Recall that a circle of radius 1 and area <em>π</em> can be inscribed in a square with sides of length 2. If we pick points at random inside the square, the probability of any given point lying in the circle is <em>π / 4</em>.
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="gadfly.js"></script>
<!-- Placed whereever you want the graphic to be rendered. -->
<div id="my_chart"></div>
<script src="output.js"></script>
<script>
draw("#my_chart");
</script>
<p>Try changing the number of simulation points by specifying the URL parameter <em>n</em>.
If the URL you used was <pre>http://localhost:8000</pre>
try changing the URL to <pre>http://localhost:8000/?n=1000</pre>
</p>
</body></html>
"""
end
get(app, "/gadfly.js") do req, res
readall(open("""$(Pkg.dir("Gadfly"))/src/gadfly.js"""))
end
get(app, "/output.js") do req, res
readall(open("output.js"))
end
function calculate(n::Integer, outfile="output.js")
#Do a Monte Carlo simulation and render the output with Gadfly
xs=convert(Array, @parallel [1-2rand() for i=1:n])
ys=convert(Array, @parallel [1-2rand() for i=1:n])
incircle=convert(Vector{Bool}, xs.^2 + ys.^2 .< 1)
pi_guess = 4sum(incircle)/n
#Plot with Gadfly
pie_plot = plot(x=xs, y=ys, color=incircle, Geom.point,
Guide.title("pi = $pi_guess (n=$n)")) #bug: π breaks D3JS output
draw(D3(outfile, 5inch, 4.5inch), pie_plot)
println("Output rendered to $outfile")
end
start(app, 8000)
In [ ]: