Let’s create our first real computational narrative in a Jupyter notebook.
Adapted from https://github.com/AaltoScienceIT/python-r-data-analysis-course
Imagine you are on a desert island and wish to compute $\pi$. You have a computer with you with Python installed but no math libraries and no Wikipedia.
Here is one way of doing it - “throwing darts” by generating random points within a square area and checking whether the points fall within the unit circle.
Calculating $\pi$ using Monte Carlo methods
- Create a new notebook, name it, and add a heading.
- Document the relevant formulas in a new cell:
- square area = $(2 r)^2$ - circle area = $\pi r^2$ - circle / square = $\pi r^2 / 4 r^2$ = $\pi / 4$ - $\pi = (circle/square) * 4$
- Add an image to explain the concept:
- Initialize variables:
N = 1000 points = 
- “Throw darts”:
hits = 0 for i in range(N): x, y = random.random(), random.random() if x**2 + y**2 < 1: hits += 1 points.append((x,y, True)) else: points.append((x,y, False))
- Plot results:
%matplotlib inline from matplotlib import pyplot x, y, colors = zip(*points) pyplot.scatter(x, y, c=colors)
- Compute final estimate of $\pi$:
fraction = hits / N 4 * fraction
What do we get from this?
Notebooks provide an intuitive way to perform interactive computational work.
Allows fast feedback in your test-code-refactor loop (see test-driven development).
Cells can be executed in any order, beware of out-of-order execution bugs!
Keyboard shortcuts can save you time and protect your wrists.