Interactive Monte Carlo Simulation.

2 min read

This post demonstrates how to embed interactive HTML/JS components into your Hugo blog posts using Shortcodes. Below is a live Monte Carlo simulation used to approximate the value of Pi.

The Simulation

The Monte Carlo method relies on repeated random sampling to obtain numerical results. In this case, we are inscribing a circle within a square.

  1. The area of the square is $ (2r)^2 = 4r^2 $.
  2. The area of the circle is $ \pi r^2 $.
  3. The ratio of the area of the circle to the area of the square is $ \frac{\pi r^2}{4r^2} = \frac{\pi}{4} $.

By randomly generating points within the square and counting how many fall inside the circle, we can estimate this ratio.

$$ \pi \approx 4 \times \frac{\text{Points Inside Circle}}{\text{Total Points}} $$

Try it out

Click Start below to begin generating random points.

Monte Carlo Pi Approximation

Total Points: 0
Points Inside: 0
Estimated Pi: -
(Actual Pi ≈ 3.14159)

Points are randomly placed in the square. The ratio of points falling inside the circle (green) to the total number of points approximates π/4.

How it’s made

This component is built using a Hugo Shortcode. The shortcode contains the HTML structure for the canvas and controls, along with the vanilla JavaScript required to run the simulation loop and render the points.

This approach allows you to enrich your content with:

  • Live data visualizations
  • Interactive calculators
  • Mini-games
  • Demonstrations of algorithms

No external libraries were used for this specific demo—just standard HTML5 Canvas APIs.