$$ \newcommand{\N}{\mathcal{N}} $$

Univariate Gaussians: notes on answers

The Gaussian note asked some questions. Here are some of the answers. I advise having a good attempt before looking at these answers. I’m also giving some guidance on how you could check answers yourself, as outside of a class you have to become sure of your own answers.

Check your understanding further

Matlab/Octave code

The full code to generate a million outcomes from a standard normal, and plot a histogram, along with its theoretical prediction:

N = 1e6;
xx = randn(N,1);
% 100 bars shows shape better than default of 10
hist(xx, 100);
[cc, bin_centres] = hist(xx, 100);
pdf = exp(-0.5*bin_centres.^2) / sqrt(2*pi);
bin_width = bin_centres(2) - bin_centres(1);
predicted_bin_heights = pdf * N * bin_width;
% Finally, plot the theoretical prediction over the histogram:
hold on;
plot(bin_centres, predicted_bin_heights, '-r', 'linewidth', 3);

Python code

The full code to generate a million outcomes from a standard normal, and plot a histogram, along with its theoretical prediction:

import numpy as np
from matplotlib import pyplot as plt

N = int(1e6) # 1e6 is a float, numpy wants int arguments
xx = np.random.randn(N)
hist_stuff = plt.hist(xx, bins=100)
bin_centres = 0.5*(hist_stuff[1][1:] + hist_stuff[1][:-1])
pdf = np.exp(-0.5*bin_centres**2) / np.sqrt(2*np.pi)
bin_width = bin_centres[1] - bin_centres[0]
predicted_bin_heights = pdf * N * bin_width
plt.plot(bin_centres, predicted_bin_heights, '-r', linewidth=3)
plt.show()