Exercises for Session 2

In [8]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

Create an array x = [-3.00, -2.99, -2.98, …, 2.98, 2.99, 3.00], and corresponding values of the standard Gaussian function.

In [9]:
dx = 0.01
x = np.arange(-3.0, 3.0+dx/2, dx)
y = 1/sqrt(2*pi) * np.exp(-x**2 / 2)

Check the result is unit normalised.

In [10]:
print(y.sum()*dx)
0.997344300831

This is not quite one as we have chopped the tails ( $>3 \sigma$ ) off the distribution.

For convenience, put x and y together in a recarray and save to a file.

In [11]:
xy = np.rec.array((x, y), names=('x', 'y'))
np.savetxt('xy.txt', xy)

Create samples of one hundred Gaussian random numbers.

In [12]:
z1 = np.random.normal(size=100)
z2 = np.random.normal(size=100)

Plot your Gaussian curve, x versus y, with axis labels

In [13]:
# better-looking plots
plt.rcParams['font.family'] = 'serif'
plt.rcParams['figure.figsize'] = (12.0, 8.0)
plt.rcParams['font.size'] = 22
In [14]:
plt.plot(x, y, lw=2)
plt.xlabel(r'$x$')
plt.ylabel(r'$y = \frac{1}{\sqrt{2}}\ \exp\left(\frac{x^2}{2}\right)$')
plt.hist(z1, normed=True, histtype='stepfilled', alpha=0.5)
_ = plt.hist(z2, normed=True, histtype='stepfilled', alpha=0.5)
# assigning the last line of a cell to something is a convenient way to avoid printing
# out what it returns (_ is a variable that contains the result of the last command)