Skip to main content

Appendix B — Python reference and setup

The experiments in this book use NumPy for arrays and random draws, SciPy for distributions, integration and optimization, and Matplotlib for graphics. Each code block is independent unless stated otherwise. You do not need a paid service or a GPU to run anything here.

B.1 Running the examples

The easiest option is to choose Open in Colab from any chapter’s practice section, or use the complete notebook list. The notebook opens directly from GitHub in Google Colab, with no local installation or upload needed. Sign in if prompted, choose File > Save a copy in Drive to save your progress, connect a runtime, and run the cells. Colab typically includes NumPy, SciPy and Matplotlib already.

If you prefer JupyterLab, choose Download .ipynb and open the saved file locally. Every notebook uses the standard Python 3 kernel.

For a local setup, install Python 3.11 or 3.12, then run in a terminal:

python -m venv probstats

On macOS or Linux activate using

source probstats/bin/activate

On Windows PowerShell:

.\probstats\Scripts\Activate.ps1

Install the packages and JupyterLab in that environment:

python -m pip install numpy scipy matplotlib jupyterlab
jupyter lab

To verify imports inside a notebook or Python file:

import numpy as np
import scipy
import matplotlib

print("NumPy:", np.__version__)
print("SciPy:", scipy.__version__)
print("Matplotlib:", matplotlib.__version__)

If using a virtual environment for the source repository, its requirements file includes the precise supported package ranges and PyYAML for build validation. The book itself renders even without a Jupyter kernel, because Python examples are visible fenced code rather than invisible execution.

B.2 Random-number generators and arrays

Create a seeded NumPy generator for reproducible draws. Generate repeated independent samples in rows:

import numpy as np

rng = np.random.default_rng(1234)
x = rng.normal(loc=3, scale=2, size=(1000,20))
print("Shape:",x.shape)
print("First five sample means:",x.mean(axis=1)[:5])
print("Empirical SE:",x.mean(axis=1).std(ddof=1))
print("Theory:",2/np.sqrt(20))

Here the shape is \((1000,20)\): one experiment per row, one observation per column. The population mean is three and standard deviation is two; NumPy’s scale parameter is not the variance.

Goal NumPy expression
Sample of size n rng.normal(0, 1, n)
Uniform on an interval rng.uniform(a, b, n)
Bernoulli sample rng.binomial(1, p, n)
Binomial counts rng.binomial(m, p, size=n)
Poisson counts rng.poisson(lam, n)
Exponential waits rng.exponential(scale=1/lam, size=n)
Gamma waits rng.gamma(shape=a, scale=1/lam, size=n)
Sample variance x.var(ddof=1)
Sample standard deviation x.std(ddof=1)
Average along rows x.mean(axis=1)
Proportion satisfying an event np.mean(x > threshold)
Quantile np.quantile(x, 0.95)

Calling the same seed again creates the same stream from its beginning. Create the generator once per experiment and draw fresh numbers for replications.

B.3 Distribution calculations with SciPy

SciPy’s statistics module supplies PMFs, densities, CDFs, survival functions, quantiles, and simulation methods. For example:

from scipy import stats

normal = stats.norm(loc=10,scale=3)
print("P(X <= 12):",normal.cdf(12))
print("P(X > 12):",normal.sf(12))
print("95th percentile:",normal.ppf(.95))
count = stats.binom(n=12,p=.4)
print("P(K = 5):",count.pmf(5))
print("P(K >= 5):",count.sf(4))

For continuous laws use .pdf(); for discrete laws use .pmf(). A CDF at \(x\) is \(P(X\le x)\), and a survival function .sf(x) is \(P(X>x)\). For integer variables, \(P(X\ge k)=P(X>k-1)\). Use survival functions for upper tails rather than subtracting CDFs from one, particularly when the probability is tiny. The percent-point function .ppf(q) is a quantile. With a frozen distribution, .mean() and .var() are theoretical moments, not sample calculations.

Mathematical parameterization SciPy call
\(N(\mu,\sigma^2)\) stats.norm(loc=mu, scale=sigma)
Exponential with rate \(\lambda\) stats.expon(scale=1/lam)
Gamma with shape \(a\), rate \(\lambda\) stats.gamma(a=a, scale=1/lam)
Beta with shapes \(a,b\) stats.beta(a,b)
Poisson with rate \(\lambda\) stats.poisson(mu=lam)
Geometric counting trials stats.geom(p=p)
Hypergeometric stats.hypergeom(M=N, n=K, N=draws)
Student t, \(\nu\) df stats.t(df=nu)
Chi-square, \(\nu\) df stats.chi2(df=nu)

B.4 Plotting without misleading yourself

For a continuous-density comparison set density=True in the histogram. This scales the bars so their total area is one, matching the PDF. For discrete data use probability bars based on counts divided by the sample size.

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
x = rng.gamma(3, .5, size=8000)
grid = np.linspace(0,5,300)
fig,ax = plt.subplots(figsize=(7,3.5))
ax.hist(x,bins=45,density=True,alpha=.55,label="Histogram")
ax.plot(grid,stats.gamma.pdf(grid,3,scale=.5),label="Exact density")
ax.set(xlabel="Waiting time",ylabel="Density")
ax.legend()
fig.tight_layout()
plt.show()

Label axes in the units of the model. Do not use a histogram of raw counts as a PDF. When comparing groups, hold relevant axes and bin ranges fixed. For extreme outliers, a robust quantile summary can be more informative than a truncated plot; label any plot limits honestly.

B.5 Stable log-space computations

Likelihoods are products of many factors. Multiplying tiny probabilities can underflow to zero even in double precision. Use their logarithms and work with sums. For logistic models, use .expit(z) and .logaddexp(0,z) to avoid directly exponentiating very large numbers.

import numpy as np
from scipy.special import expit, logsumexp

log_weights = np.array([-1002.,-999.,-1000.])
weights = np.exp(log_weights-logsumexp(log_weights))
print("Normalized weights:",weights,weights.sum())
z = np.array([-1000.,-2.,0.,2.,1000.])
print("Sigmoid:",expit(z))
print("Stable log(1 + exp(z)):",np.logaddexp(0,z))

B.6 A repeatable investigation checklist

  1. Define the target probability or parameter and write its formula.
  2. Generate independent replications appropriate to the model.
  3. Calculate the statistic in the intended direction and units.
  4. Compare numerical results with the exact expression or theorem.
  5. Report Monte Carlo uncertainty, not just a single decimal.
  6. Alter one assumption deliberately and predict how the results change.

If a book example produces an unexpected number, first check parameter order, standard deviation versus variance, rate versus scale, the shape of the arrays, and whether the exercise requires a one-sided or two-sided event.