Demo notebook

Teake Nutma t.a.nutma@rug.nl

14-01-2019

I will be using a couple of keyboard shortcuts that are available in Jupyter:

# Command mode
Enter: Go to edit mode
a:     Insert cell above
b:     Insert cell below
x:     Cut cell
m:     Change cell to markdown (text)
y:     Change cell to code

# Edit mode:
Esc:         Go to command mode
Shift+Enter: Run cell
Tab:         Code completion

You can press H to show them all.

In [1]:
# This is code.
# You can run it with Shift+Enter
2 + 2
Out[1]:
4

This is text.

This is text with an inline formula: $e^{i\pi} + 1 = 0$.

This is text with a centered formula:

$$ R_{\mu\nu} - \tfrac 1 2 g_{\mu\nu} + \Lambda_{\mu\nu} = \frac{8\pi G}{c^4} T_{\mu\nu} $$

We can also define a function:

In [1]:
def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fibonacci(n-1) + fibonacci(n-2)

Let's see if it works:

In [2]:
fibonacci(10)
Out[2]:
55
In [3]:
fibs = [fibonacci(n) for n in range(1,11)]
fibs
Out[3]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

We can also plot it:

In [4]:
import matplotlib.pyplot as plt
In [5]:
plt.plot(fibs)
Out[5]:
[<matplotlib.lines.Line2D at 0x11e8d6e10>]

Let's define another function:

In [6]:
import math
In [7]:
def binomial(n,p):
    return math.factorial(n) // (math.factorial(n-p) * math.factorial(p))
In [8]:
bins = [binomial(10, p) for p in range(0, 11)]
bins
Out[8]:
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]

We can computer the sum of this, which turns out to be $2^{10}$.

In [9]:
sum(bins)
Out[9]:
1024

Plot it:

In [10]:
plt.plot(bins)
Out[10]:
[<matplotlib.lines.Line2D at 0x11e9c3b38>]

Let's define a convenience function that will give us a list of binomials for given $n$:

In [11]:
def binomial_list(n):
    return [binomial(n, p) for p in range(0, n+1)]

We can now easily plot this:

In [12]:
plt.plot(binomial_list(30))
Out[12]:
[<matplotlib.lines.Line2D at 0x11ea28f28>]

Let's try it with on a log scale:

In [13]:
plt.semilogy(binomial_list(10))
Out[13]:
[<matplotlib.lines.Line2D at 0x11eaba208>]
In [14]:
from ipywidgets import interact

def plotbinomials(n):
    plt.semilogy(binomial_list(n))
    
interact(plotbinomials, n=(1,20))
Out[14]:
<function __main__.plotbinomials(n)>

This nicely demonstrates the limiting behaviour of the binomial distribution.

Lastly, let's double-check that $\sum_{p=0}^n \binom{n}{p} = 2^n$:

In [15]:
[sum(binomial_list(n)) for n in range(1,11)]
Out[15]:
[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]