# Exercises for Session 2¶

In [1]:
%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 [2]:
dx = 0.01
x = np.arange(-3.0, 3.0+dx/2, dx)
y = 1/np.sqrt(2*np.pi) * np.exp(-x**2 / 2)


Check the result is unit normalised.

In [3]:
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 [4]:
xy = np.rec.array((x, y), names=('x', 'y'))
np.savetxt('xy.txt', xy)


Create samples of one hundred Gaussian random numbers.

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


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

In [6]:
# better-looking plots
plt.rcParams['font.family'] = 'serif'
plt.rcParams['figure.figsize'] = (12.0, 8.0)
plt.rcParams['font.size'] = 22

In [7]:
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)
# you can also end the line with a semicolon