1.5 Probabilistic Arithmetic
1.5 Probabilistic Arithmetic
In Section 1.4 we were interested in how the visiting times of a patient would become distributed over periods of half a year after many visits. We can formalize this problem as follows for one patient. Let \(X_k\) be the \(k\)th inter-arrival time, and write \(C\) for the length of the interval in which the patient has to see a doctor; here \(C\) is half a year. Then the arrival times modulo \(C\) satisfy
\begin{align*} Z_{k} &= Z_{k-1} + X_{k} \bmod C, & Z_{0} &= 0, \end{align*}where \(X_{k}\bmod C\) is the remainder of \(X_{k}/C.\) To compute the distribution of \(Z_k\) we need to be able to compute the distribution of \(Y_{k} = Z_{k-1} + X_k,\) and then find the distribution of \(f(Y_k)\) where \(f(x) = x \bmod C.\) Clearly, this is a very unattractive task to carry out by hand. In this section we develop algorithms that allow a computer to carry out this tedious work.
More generally, later sections require numerical work to gain insight into the behavior of stochastic processes. We therefore develop a class of random variables that supports probabilistic arithmetic. The emphasis is on reusable algorithmic patterns: how probability distributions are stored, how methods transform and combine random variables, and why these methods work. At the end of this section, we use these algorithms to study the distribution of \(\set{Z_k}\) discussed above.
Let us start by making explicit what we mean by a pattern. As a first pattern, consider the \(+\) operator. Suppose that we only know how to do addition on the positive integers.1For example: \(3+5=8.\) Observe that the definition of addition on integers cannot be directly applied to rationals. To add fractions, we need to extend the symbol \(+\) to the following procedure: make the denominators of the fractions identical, and then add the numerators.2\(1/3+1/2 = 2/6 + 3/6 = (2+3)/6 = 5/6.\) However, this procedure does not work to compute \(\sqrt 2 + \sqrt 3.\)3\(\sqrt 2\) and \(\sqrt 3\) are not rationals so we cannot make the denominators equal. To add general real numbers, we need to extend the definition of \(+\) yet further.4One way is like this: \(\sqrt 2 + \sqrt 3 = \Sup{x + y : x, y \in \Q, x^{2} \leq 2, y^{2} \leq 3}.\) Next, we need to define addition for complex numbers, vectors, matrices, \(\ldots\). In summary, when learning mathematics, we have been silently overloading the \(+\) operator to many different situations.
In our present case, we write \(X+Y\) for two independent rvs to mean the convolution:
\begin{equation*} \P{X+Y=z} = \sum_{i} \sum_{j} p_{i} q_{j} \1{i+j=z}, \tag{1.5.1} \end{equation*}where \(p_{i} = \P{X=i},\) \(q_j = \P{Y=j}\) and the indicator \(\1{A} = 1\) if the event \(A\) occurs, and \(0\) otherwise. Below we express this as an algorithm.5For addition there exists a much faster method based on Fast Fourier transforms.
Thus, the first pattern that helps us to reason in more abstract ways about problems is to use operator overloading.
This brings us to a second pattern: observe that the expression \(X+Y\) combines two rvs \(X\) and \(Y\) and then applies some function. Similarly, the operations \(X-Y,\) \(XY,\) \(\Max{X, Y}\) are all functions applied to two independent rvs. What we therefore need is a method to compute the pmf of a new rv \(f(X,Y),\) where \(f\) is some general binary function.6A binary function depends on two arguments.
We identify a third pattern when we realize that to compute \(\V X,\) we need \(\E{X^{2}}.\) But \(\E{X^{2}}\) is the expectation of the rv \(g(X)\) where \(g(x) = x^{2}.\) So, we also need a method to compute the pmf of the rv \(g(X),\) where now \(g\) is some general unary function.7A unary function depends on just one argument.
In summary, we want to support the following operations on rvs:
- operator overloading for addition, subtraction, and other arithmetical operations;
- the application of a unary function to obtain a new rv;
- the application of a binary function.
We collect these operations in a class \(\cl{RV}.\) Then we can write \(X+Y,\) \(S-X,\) and \(f(X)\) in pseudocode, just as in mathematics. However, we first need to introduce some computer science concepts.
A useful data structure for storing the pmf of a discrete rv is a map, as constructed by \(\pr{Map}\) in Alg. 1.2.13. Its keys are the possible values of the rv, and the value stored under each key is its probability. Since values outside the support have probability zero, we use the default value zero. We denote the pmf map of an rv \(X\) by \(p_X,\) so that \(p_X(x)=\P{X=x}.\)
\begin{algorithm}
\caption{Store two probability mass functions.}
\begin{algorithmic}[1]
\State \(p_X\gets\pr{Map}()\) \Comment{Initialize $p_{X}$.}
\State \(p_X(1)\gets1/2,\) \(p_X(2)\gets1/2\)
\State \(p_Y\gets\pr{Map}()\)
\State \(p_Y(1)\gets1/2,\) \(p_Y(2)\gets1/2\)
\end{algorithmic}
\end{algorithm}
Python code
# Run these Python blocks in reading order.
from collections import defaultdict
from fractions import Fraction
p_X = defaultdict(int)
p_X[1] = Fraction(1, 2)
p_X[2] = Fraction(1, 2)
p_Y = defaultdict(int)
p_Y[1] = Fraction(1, 2)
p_Y[2] = Fraction(1, 2)
R code
# Run the R examples from Algorithmic Patterns first, then these in order.
p_X <- Map()
Set(p_X, 1, 1/2)
Set(p_X, 2, 1/2)
p_Y <- Map()
Set(p_Y, 1, 1/2)
Set(p_Y, 2, 1/2)
It is obvious that the pmf map \(p_Z\) for \(Z=X+Y\) should satisfy \(p_Z(2)=1/4,\) \(p_Z(3)=1/2,\) and \(p_Z(4)=1/4.\) Let us use (1.5.1) to compute the pmf of \(Z=X+Y.\)
\begin{algorithm}
\caption{Compute the pmf of the sum.}
\begin{algorithmic}[1]
\State \textbf{Input:} pmf maps \(p_X,\, p_Y.\)
\State \textbf{Output:} pmf map \(p_Z\) for \(X+Y.\)
\State \(p_Z\gets\pr{Map}()\)
\For{\(i\in\qb{1,\, 2}\)}
\For{\(j\in\qb{1,\, 2}\)}
\State \(p_Z(i+j)\xleftarrow{+} p_X(i)\cdot p_Y(j)\)
\EndFor
\EndFor
\Return \(p_Z\)
\end{algorithmic}
\end{algorithm}
Python code
p_Z = defaultdict(int)
for i in [1, 2]:
for j in [1, 2]:
p_Z[i + j] += p_X[i] * p_Y[j]
print(dict(p_Z)) # {2: 1/4, 3: 1/2, 4: 1/4}, with Fraction values.
R code
p_Z <- Map()
for (i in c(1, 2)) {
for (j in c(1, 2)) {
Set(p_Z, i + j, p_Z(i + j) + p_X(i) * p_Y(j))
}
}
print(Values(p_Z)) # 1/4, 1/2, 1/4.
Because \(p_Z\) is a map with default value zero, the first contribution to a key is added to zero. Later contributions are added to the value already stored under that key. In particular, the two pairs \((1,2)\) and \((2,1)\) each add \(1/4\) to \(p_Z(3).\) Thus, the algorithm returns \(p_Z(2)=1/4,\) \(p_Z(3)=1/2,\) and \(p_Z(4)=1/4.\)
The above algorithm assumes that mathematically equal keys have the same representation in the computer. This requires care when the keys are stored as floating-point numbers. Most real numbers cannot be represented exactly with finitely many digits. Consequently, two expressions that are mathematically equal, such as \(1/3\) and \(1-2/3,\) can be stored as slightly different numbers. An implementation of \(\pr{Map}\) in a real computer language then treats them as different keys and does not combine their probabilities. This is a general problem of computer arithmetic, not a problem specific to a programming language. We avoid it by using exact numbers, such as integers or fractions, whenever possible. Otherwise, we round all keys to an agreed precision before storing them.
The function \(\pr{ToFraction}\) of Alg. 1.5.3 replaces a number \(x\in \R\) by a nearby fraction, rounded to \(d\) decimal places. It first uses denominator \(10^d\) and then reduces the fraction using the greatest common divisor.8The greatest common divisor can be computed with Euclid’s algorithm. See Euclidean algorithm for its implementation. Keeping this conversion in a separate function hides its details from the algorithms that use it. If we later change the precision or the conversion rule, we only have to change \(\pr{ToFraction}.\)
\begin{algorithm}
\caption{Convert a number to a fraction.}
\begin{algorithmic}[1]
\State \textbf{Input:} a number \(x\) and precision \(d.\)
\State \textbf{Output:} a reduced fraction \(a/b.\)
\Function{ToFraction}{\(x,\, d = 10\)}
\State \(q\gets10^d\)
\State \(p\gets\operatorname{round}(x\cdot q)\)
\State \(g\gets\pr{GCD}(|p|,\, q)\)
\Return \(p/g, q/g\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def ToFraction(x, d=10):
q = 10**d
p = round(x * q)
return Fraction(p, q) # Fraction reduces numerator and denominator.
R code
ToFraction <- function(x, d = 10) {
q <- 10^d
p <- round(x * q)
a <- abs(p)
b <- q
while (b != 0) {
remainder <- a %% b
a <- b
b <- remainder
}
c(p / a, q / a) # Reduced numerator and denominator.
}
The function \(\pr{MakePMF}\) of Alg. 1.5.4 uses the conversion to fractions to construct a pmf map from a map of outcomes and non-negative weights. It first converts every outcome with \(\pr{ToFraction}.\) When two outcomes are converted to the same fraction, their weights are added. Finally, \(\pr{NormalizeMap},\) Alg. 1.5.5, makes the stored weights sum to one. Rounding the outcomes and discarding small weights makes the resulting pmf a numerical approximation to the original distribution.
\begin{algorithm}
\caption{Construct a probability mass function.}
\begin{algorithmic}[1]
\State \textbf{Input:} a finite map \(w\) with non-negative values and positive sum.
\State \textbf{Output:} a pmf map \(p.\)
\Function{MakePMF}{\(w\)}
\State \(r\gets\pr{Map}()\)
\For{\(x\in\pr{Keys}(w)\)}
\State \(r(\pr{ToFraction}(x))\xleftarrow{+}w(x)\)
\EndFor
\Return \(\pr{NormalizeMap}(r)\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def MakePMF(w):
r = defaultdict(int)
for x, weight in w.items():
r[ToFraction(x)] += weight
return NormalizeMap(r)
R code
MakePMF <- function(w) {
r <- Map()
for (x in Keys(w)) {
fraction <- ToFraction(x)
# Base R stores the reduced fraction's value as a floating-point key.
key <- fraction[[1]] / fraction[[2]]
Set(r, key, r(key) + w(x))
}
NormalizeMap(r)
}
The function \(\pr{Normalize}\) of Alg. 1.2.8 normalizes a list of weights. For the given map \(\var{w},\) we store the weights in a map whose keys are the possible outcomes. It then removes entries whose relative weight does not exceed the default numerical threshold \(\epsilon=10^{-16},\) and then normalizes the remaining weights.
\begin{algorithm}
\caption{Normalize the values stored in a map.}
\begin{algorithmic}[1]
\State \textbf{Input:} a finite map \(w\) with non-negative values and positive sum; threshold \(\epsilon.\)
\State \textbf{Output:} a map \(p\) whose values sum to one.
\Function{NormalizeMap}{\(w,\, \epsilon = 10^{-16}\)}
\State \(T\gets\pr{Sum}\rb{\pr{Values}(w)}\)
\State \(S\gets\pr{Filter}\rb{\pr{Keys}(w), \lambdafun{k}{w(k)/T>\epsilon}}\)
\State \(\var{total}\gets\pr{Sum}\rb{\qb{w(k):k\in S}}\)
\State \(V\gets\pr{Apply}\rb{S, \lambdafun{k}{w(k)/\var{total}}}\)
\Return \(\pr{MakeMap}\rb{\var{keys}=S,\, \var{values}=V}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def NormalizeMap(w, epsilon=1e-16):
T = sum(w.values())
S = [k for k in w if w[k] / T > epsilon]
total = sum(w[k] for k in S)
return defaultdict(int, {k: w[k] / total for k in S})
R code
NormalizeMap <- function(w, epsilon = 1e-16) {
T <- Sum(Values(w))
S <- Filter(Keys(w), function(k) w(k) / T > epsilon)
total <- Sum(Apply(S, w))
V <- Apply(S, function(k) w(k) / total)
MakeMap(keys = S, values = V)
}
The cumulative probabilities of an rv give its cdf, as we will see below. To compute them, we need the running totals of a list, as computed by \(\pr{CumSum}.\)
\begin{algorithm}
\caption{Compute the cumulative sums of a list.}
\begin{algorithmic}[1]
\State \textbf{Input:} a list \(A=\qb{a_1,\ldots,a_n}.\)
\State \textbf{Output:} the list \(C=\qb{C_1,\ldots,C_n}\) of running totals of \(A.\)
\Function{CumSum}{\(A\)}
\State \(C_0\gets0\)
\For{\(k=1,\, \ldots,\, n\)}
\State \(C_k\gets C_{k-1}+a_k\)
\EndFor
\Return \(C\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
from itertools import accumulate
def CumSum(A):
return list(accumulate(A))
R code
CumSum <- function(A) {
as.list(cumsum(as.numeric(unlist(A))))
}
We now collect the pmf map and the operations on it in one class. An rv is fully described by its pmf map. The constructor of the class \(\cl{RV}\) receives a map \(w\) of non-negative weights and stores the pmf map \(\var{pmf}\gets\pr{MakePMF}(w);\) thus it rounds the outcomes with \(\pr{ToFraction}\) and normalizes the weights. The methods \(\pr{Keys}\) and \(\pr{Values}\) return the keys and values of \(\var{pmf},\) so \(X.\pr{Keys}\rb{}\) is the support of \(X,\) and we write \(X(x)\) for \(\var{pmf}(x)=\P{X=x}.\) Furthermore, the class provides methods for expectations, the cdf, and simulation, and it overloads the arithmetic operators. In the methods, \(X\) denotes the object itself.
\begin{algorithm}
\caption{The class of discrete random variables.}
\begin{algorithmic}[1]
\State \textbf{Input:} a finite map \(w\) with non-negative values and positive sum.
\State \textbf{Output:} an rv \(X\) with pmf map \(\pr{MakePMF}(w).\)
\State \textbf{class} \(\cl{RV}\rb{w}\)
\State \(\quad\) \textbf{instance variables:}
\State \(\quad\quad \var{pmf}\gets\pr{MakePMF}\rb{w}\)
\State \(\quad\quad S\gets\pr{QSort}\rb{\pr{Keys}(\var{pmf})}\) \Comment{Sorted support \(\qb{s_1,\ldots,s_n}.\)}
\State \(\quad\quad C\gets\pr{CumSum}\rb{\qb{\var{pmf}(s):s\in S}}\) \Comment{\(c_k=\P{X\leq s_k}.\)}
\State \(\quad\) \textbf{properties:}
\State \(\quad\quad \var{mean}\gets\pr{E}\rb{\lambdafun{x}{x}}\)
\State \(\quad\quad \var{second\_moment}\gets\pr{E}\rb{\lambdafun{x}{x^2}}\)
\State \(\quad\quad \var{variance}\gets\var{second\_moment}-\var{mean}^2\)
\State \(\quad\quad \var{std}\gets\sqrt{\var{variance}}\)
\State \(\quad\) \textbf{methods:}
\State \(\quad\quad X(x)\gets\var{pmf}(x)\) \Comment{So \(X(x)=\P{X=x}.\)}
\State \(\quad\quad \pr{Keys}\rb{}\gets\pr{Keys}\rb{\var{pmf}}\)
\State \(\quad\quad \pr{Values}\rb{}\gets\pr{Values}\rb{\var{pmf}}\)
\State \(\quad\quad \pr{E}\gets\lambdafun{f}{\pr{Sum}\rb{\qb{f(x)\cdot X(x):x\in X.\pr{Keys}\rb{}}}}\)
\State \(\quad\quad \pr{CDF}\rb{x}\)
\State \(\quad\quad \pr{Survivor}\gets\lambdafun{x}{1-\pr{CDF}\rb{x}}\)
\State \(\quad\quad \pr{Simulate}\rb{N=1}\)
\State \(\quad\quad \pr{Transform}\rb{f}\) \Comment{The rv \(f(X).\)}
\State \(\quad\quad \pr{Condition}\rb{A}\) \Comment{The rv \(X\) conditioned on \(A(X).\)}
\end{algorithmic}
\end{algorithm}
Python code
from math import sqrt
class RV:
def __init__(self, w):
self.pmf = MakePMF(w)
self.S = QSort(list(self.pmf.keys())) # Sorted support.
self.C = CumSum([self.pmf[s] for s in self.S]) # C[k-1] = P(X <= S[k-1]).
@property
def mean(self):
return self.E(lambda x: x)
@property
def second_moment(self):
return self.E(lambda x: x**2)
@property
def variance(self):
return self.second_moment - self.mean**2
@property
def std(self):
return sqrt(self.variance)
def __call__(self, x): # X(x) = P(X = x).
# Round x as MakePMF rounds the keys; unlike pmf[x], get does not store x.
return self.pmf.get(ToFraction(x), 0)
def keys(self):
return list(self.pmf.keys())
def values(self):
return list(self.pmf.values())
def E(self, f):
return Sum([f(x) * self(x) for x in self.keys()])
def survivor(self, x):
return 1 - self.cdf(x)
# The methods cdf, simulate, transform, and condition follow below.
R code
# An rv is a function x -> P(X = x) of class "RV". It shares the store of
# its pmf map, so Keys(X) and Values(X) work as for a map.
RV <- function(w) {
pmf <- MakePMF(w)
S <- QSort(Keys(pmf)) # Sorted support.
C <- CumSum(Apply(S, pmf)) # C[[k]] = P(X <= S[[k]]).
X <- function(x) {
# Round x as MakePMF rounds the keys; unlike pmf(x), match does not store x.
r <- ToFraction(x)
i <- match(r[[1]] / r[[2]], unlist(Keys(pmf)))
if (is.na(i)) 0 else Values(pmf)[[i]]
}
attr(X, 'store') <- attr(pmf, 'store')
attr(X, 'S') <- S
attr(X, 'C') <- C
class(X) <- "RV"
X
}
E <- function(X, f) Sum(Apply(Keys(X), function(x) f(x) * X(x)))
mean.RV <- function(x, ...) E(x, function(y) y) # R's mean(X) calls this.
second_moment <- function(X) E(X, function(x) x^2)
variance <- function(X) second_moment(X) - mean(X)^2
std <- function(X) sqrt(variance(X))
Survivor <- function(X, x) 1 - CDF(X, x)
# CDF, Simulate, Transform, and Condition follow below.
The method \(\pr{E}\) applies \(f\) to every possible value of \(X\) to compute \(\E{f(X)}.\) With it, the properties give the mean, the second moment, the variance, and the standard deviation of \(X,\) as in \(X.\var{mean}=\E X.\) A property is evaluated each time it is read.
In principle, \(\pr{E}\) also gives the cdf, because \(F_X(x)=\P{X\leq x}=\E{\1{X\leq x}}\) equals \(X.\pr{E}\rb{\lambdafun{y}{\1{y\leq x}}}.\) However, this sums over all outcomes at each call. To evaluate the cdf at many different values of \(x,\) the constructor computes the sorted support \(S\) and the cumulative probabilities \(C\) once. To find \(\P{X\leq x},\) it then suffices to find how many entries of \(S\) are no larger than \(x.\) \(\pr{SearchSorted},\) Alg. 1.5.19, returns this number \(k.\) We explain how it works at the end of the main text. When \(k=0,\) \(x<s_1\) and the cdf is zero; otherwise it is \(c_k.\)
\begin{algorithm}
\caption{The cdf of an rv.}
\begin{algorithmic}[1]
\State \textbf{Input:} a number \(x.\)
\State \textbf{Output:} \(\P{X\leq x}.\)
\Function{RV.CDF}{\(x\)}
\State \(k\gets\pr{SearchSorted}\rb{S,\, x}\)
\If{\(k==0\)}
\Return \(0\)
\EndIf
\Return \(c_k\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def cdf(self, x):
k = SearchSorted(self.S, x)
if k == 0:
return 0
return self.C[k - 1] # Python lists start at index 0.
RV.cdf = cdf # Make cdf a method of RV.
R code
CDF <- function(X, x) {
k <- SearchSorted(attr(X, 'S'), x)
if (k == 0) return(0)
attr(X, 'C')[[k]]
}
For example, let \(X\) have \(\P{X=1}=5/12,\) \(\P{X=2}=1/3,\) and \(\P{X=3}=1/4.\)
\begin{algorithm}
\begin{algorithmic}[1]
\State \(w\gets\pr{Map}()\)
\State \(w(3)\gets1/4,\quad w(2)\gets1/3,\quad w(1)\gets5/12\)
\State \(X\gets\cl{RV}\rb{w}\) \Comment{\(S=\qb{1,\,2,\,3}\) and \(C=\qb{5/12,\,3/4,\,1}.\)}
\State \(X.\pr{CDF}\rb{1.1}\) \Comment{Returns \(5/12.\)}
\State \(X.\pr{Survivor}\rb{1.1}\) \Comment{Returns \(7/12.\)}
\end{algorithmic}
\end{algorithm}
We can now also generate simulated realizations of \(X.\) Let \(F\) be the cdf of \(X\) and \(U\sim\Unif{[0,1]}.\) The inverse-cdf method returns the smallest support value \(s_k\) for which \(F(s_k)\geq U.\) This has the required distribution because
\begin{align*} \P{F^{-1}(U)\leq x}=\P{U\leq F(x)}=F(x). \end{align*}The method \(\pr{Simulate}\) applies \(\pr{SearchSorted}\) to the cumulative probabilities. When \(U=c_k,\) it returns \(s_k;\) otherwise it returns the next support value \(s_{k+1}.\) The special case \(k=0\) returns the first support value.
\begin{algorithm}
\caption{Generate \(N\) simulated realizations of an rv.}
\begin{algorithmic}[1]
\State \textbf{Input:} number of draws \(N.\)
\State \textbf{Output:} \(N\) simulated values \(R=\qb{R_1,\ldots,R_N}\) of \(X.\)
\Function{RV.Simulate}{\(N=1\)}
\For{\(j=1,\, \ldots,\, N\)}
\State Generate \(u\sim\Unif{[0,\, 1]}.\)
\State \(k\gets\pr{SearchSorted}(C,\, u)\)
\If{\(k==0\)}
\State \(R_j\gets s_1\)
\ElsIf{\(c_k==u\)}
\State \(R_j\gets s_k\)
\Else
\State \(R_j\gets s_{k+1}\)
\EndIf
\EndFor
\Return \(R\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
from random import random
def simulate(self, N=1):
S, C = self.S, self.C
R = [None] * N
for j in range(N):
u = random()
k = SearchSorted(C, u)
if k == 0:
R[j] = S[0]
elif C[k - 1] == u:
R[j] = S[k - 1]
else:
R[j] = S[k] # s_{k+1} in the pseudocode.
return R
RV.simulate = simulate
R code
Simulate <- function(X, N = 1) {
S <- attr(X, 'S')
C <- attr(X, 'C')
R <- numeric(N)
for (j in seq_len(N)) {
u <- runif(1)
k <- SearchSorted(C, u)
if (k == 0) {
R[j] <- S[[1]]
} else if (C[[k]] == u) {
R[j] <- S[[k]]
} else {
R[j] <- S[[k + 1]]
}
}
R
}
The two remaining patterns are unary and binary functions. For a unary function \(f,\) let \(Z=f(X).\) Its pmf satisfies
\begin{equation*} \P{Z=z}=\sum_{x\in X.\pr{Keys}\rb{}}X(x)\1{f(x)=z}. \tag{1.5.2} \end{equation*}The method \(\pr{Transform}\) implements this rule by applying \(f\) to each possible value of \(X.\) Different values of \(X\) can produce the same value \(z=f(x),\) so their probability masses accumulate in the map \(w.\) We write \(f(X)\) for \(X.\pr{Transform}\rb{f}.\)
\begin{algorithm}
\caption{Construct the rv \(f(X).\)}
\begin{algorithmic}[1]
\State \textbf{Input:} function \(f.\)
\State \textbf{Output:} the rv \(f(X).\)
\Function{RV.Transform}{\(f\)}
\State \(w\gets\pr{Map}()\)
\For{\(x\in X.\pr{Keys}\rb{}\)}
\State \(w(f(x))\xleftarrow{+}X(x)\)
\EndFor
\Return \(\cl{RV}\rb{w}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def transform(self, f):
w = defaultdict(int)
for x in self.keys():
w[f(x)] += self(x)
return RV(w)
RV.transform = transform
R code
Transform <- function(X, f) {
w <- Map()
for (x in Keys(X)) {
z <- f(x)
Set(w, z, w(z) + X(x))
}
RV(w)
}
Supporting binary functions works the same as addition in (1.5.1). The function \(\pr{BinaryTransform}\) replaces the particular function \(x+y\) by a general binary function \(f(x,y).\) When several pairs produce the same value \(z,\) their probability masses accumulate in the map \(w.\) As it combines two rvs, we define it as a function, not as a method of one of them.
\begin{algorithm}
\caption{Construct the rv \(f(X,Y)\) where \(X,Y\) are independent rvs.}
\begin{algorithmic}[1]
\State \textbf{Input:} independent rvs \(X,\, Y,\) binary function \(f.\)
\State \textbf{Output:} the rv \(f(X,\, Y).\)
\Function{BinaryTransform}{\(X,\, Y,\, f\)}
\State \(w\gets\pr{Map}()\)
\For{\(x\in X.\pr{Keys}\rb{}\)}
\For{\(y\in Y.\pr{Keys}\rb{}\)}
\State \(w(f(x,\, y))\xleftarrow{+}X(x)\cdot Y(y)\)
\EndFor
\EndFor
\Return \(\cl{RV}\rb{w}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def BinaryTransform(X, Y, f):
w = defaultdict(int)
for x in X.keys():
for y in Y.keys():
w[f(x, y)] += X(x) * Y(y)
return RV(w)
R code
BinaryTransform <- function(X, Y, f) {
w <- Map()
for (x in Keys(X)) {
for (y in Keys(Y)) {
z <- f(x, y)
Set(w, z, w(z) + X(x) * Y(y))
}
}
RV(w)
}
With these two transforms, we can overload the arithmetic operators. A constant rv takes one value \(c\) with probability one. In an operation with an rv, a number \(c\) stands for \(\pr{Constant}\rb{c};\) for instance, \(S-X\) stands for \(\pr{Constant}\rb{S}-X.\)
\begin{algorithm}
\caption{Construct a constant rv.}
\begin{algorithmic}[1]
\State \textbf{Input:} value \(c.\)
\State \textbf{Output:} the rv that equals \(c\) with probability one.
\Function{Constant}{\(c\)}
\State \(w\gets\pr{Map}(),\) \(w(c)\gets1\)
\Return \(\cl{RV}\rb{w}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def Constant(c):
w = defaultdict(int)
w[c] = Fraction(1) # With an int 1, NormalizeMap would return the float 1.0.
return RV(w)
def AsRV(Y): # In an operation with an rv, a number c stands for Constant(c).
return Y if isinstance(Y, RV) else Constant(Y)
R code
Constant <- function(c) {
w <- Map()
Set(w, c, 1)
RV(w)
}
AsRV <- function(Y) { # In an operation with an rv, a number c stands for Constant(c).
if (inherits(Y, "RV")) Y else Constant(Y)
}
Alg. 1.5.14 lists the operators of the class \(\cl{RV}.\) Each is a unary or binary transform, or a combination of earlier operators. For instance, subtraction is addition of the negative, and \(X^-=\Max{0,-X}=(-X)^+.\)
\begin{algorithm}
\caption{The arithmetic operators of the class \(\cl{RV}\) for independent rvs \(X,\, Y,\) a number \(C,\) and functions \(\min\) and \(\max.\)}
\begin{algorithmic}[1]
\State \(-X\gets X.\pr{Transform}\rb{\lambdafun{x}{-x}}\)
\State \(X+Y\gets\pr{BinaryTransform}\rb{X,\, Y,\, \lambdafun{(x,\, y)}{x+y}}\)
\State \(X-Y\gets X+(-Y)\)
\State \(X\cdot Y\gets\pr{BinaryTransform}\rb{X,\, Y,\, \lambdafun{(x,\, y)}{x\cdot y}}\)
\State \(\Min{X,\, Y}\gets\pr{BinaryTransform}\rb{X,\, Y,\, \lambdafun{(x,\, y)}{\Min{x,\, y}}}\)
\State \(\Max{X,\, Y}\gets\pr{BinaryTransform}\rb{X,\, Y,\, \lambdafun{(x,\, y)}{\Max{x,\, y}}}\)
\State \(X^+\gets\Max{0,\, X}\)
\State \(X^-\gets(-X)^+\)
\State \(X\bmod C\gets X.\pr{Transform}\rb{\lambdafun{x}{x\bmod C}}\)
\end{algorithmic}
\end{algorithm}
Python code
# Python calls these methods for -X, X + Y, c + X, X - Y, c - X, X * Y, c * X, X % C.
RV.__neg__ = lambda X: X.transform(lambda x: -x)
RV.__add__ = lambda X, Y: BinaryTransform(X, AsRV(Y), lambda x, y: x + y)
RV.__radd__ = lambda X, c: AsRV(c) + X
RV.__sub__ = lambda X, Y: X + (-AsRV(Y))
RV.__rsub__ = lambda X, c: AsRV(c) - X
RV.__mul__ = lambda X, Y: BinaryTransform(X, AsRV(Y), lambda x, y: x * y)
RV.__rmul__ = lambda X, c: AsRV(c) * X
RV.__mod__ = lambda X, C: X.transform(lambda x: x % C)
# Python's min and max cannot be overloaded, so we use Min and Max.
def Min(X, Y):
return BinaryTransform(AsRV(X), AsRV(Y), lambda x, y: min(x, y))
def Max(X, Y):
return BinaryTransform(AsRV(X), AsRV(Y), lambda x, y: max(x, y))
def PositivePart(X): # X^+
return Max(0, X)
def NegativePart(X): # X^-
return PositivePart(-X)
R code
# R calls Ops.RV for -X, X + Y, X - Y, X * Y, and X %% C when X or Y is an RV.
Ops.RV <- function(e1, e2) {
if (missing(e2)) { # Unary operator.
if (.Generic == "-") return(Transform(e1, function(x) -x))
stop("Unary ", .Generic, " is not defined for RV.")
}
X <- AsRV(e1)
switch(.Generic,
"+" = BinaryTransform(X, AsRV(e2), function(x, y) x + y),
"-" = X + (-AsRV(e2)),
"*" = BinaryTransform(X, AsRV(e2), function(x, y) x * y),
"%%" = Transform(X, function(x) x %% e2),
stop("Operator ", .Generic, " is not defined for RV."))
}
# R's min and max dispatch on their first argument only, so we use Min and Max.
Min <- function(X, Y) BinaryTransform(AsRV(X), AsRV(Y), function(x, y) min(x, y))
Max <- function(X, Y) BinaryTransform(AsRV(X), AsRV(Y), function(x, y) max(x, y))
PositivePart <- function(X) Max(0, X) # X^+
NegativePart <- function(X) PositivePart(-X) # X^-
Here is an example. It is obvious that \(Z=X+Y\) satisfies \(Z(2)=1/4,\) \(Z(3)=1/2,\) and \(Z(4)=1/4.\)
\begin{algorithm}
\begin{algorithmic}[1]
\State \(w\gets\pr{Map}(),\) \(w(1)\gets1,\) \(w(2)\gets1\)
\State \(X,\, Y\gets\cl{RV}\rb{w},\, \cl{RV}\rb{w}\) \Comment{\(X(1)=X(2)=1/2.\)}
\State \(Z\gets X+Y\) \Comment{\(Z(2)=1/4,\) \(Z(3)=1/2,\) \(Z(4)=1/4.\)}
\State \(Z.\var{mean}\) \Comment{Returns \(3.\)}
\State \(Z.\pr{CDF}\rb{3}\) \Comment{Returns \(3/4.\)}
\State \(V\gets5-Z\) \Comment{\(V(1)=1/4,\) \(V(2)=1/2,\) \(V(3)=1/4.\)}
\State \(V^+.\var{mean}\) \Comment{Returns \(2.\)}
\end{algorithmic}
\end{algorithm}
The \(N\)-fold convolution of \(X\) is the rv \(X_1+\cdots+X_N,\) where the \(X_k\) are independent copies of \(X.\) For \(N=0,\) the sum is zero. We use addition as the accumulator function and \(\pr{Constant}\rb{0}\) as its start value in Alg. 1.2.5.
\begin{algorithm}
\caption{Construct the sum of \(N\) independent copies of an rv.}
\begin{algorithmic}[1]
\State \textbf{Input:} rv \(X,\) number of copies \(N.\)
\State \textbf{Output:} the sum of \(N\) independent copies of \(X.\)
\Function{Convolution}{\(X,\, N\)}
\Return \(\pr{Accumulate}\rb{\qb{X:k=1,\, \ldots,\, N},\, \lambdafun{(Y,\, Z)}{Y+Z},\, \pr{Constant}\rb{0}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def Convolution(X, N):
return Accumulate([X for k in range(N)], lambda Y, Z: Y + Z, Constant(0))
R code
Convolution <- function(X, N) {
Accumulate(rep(list(X), N), function(Y, Z) Y + Z, Constant(0))
}
Sometimes we need an rv conditioned on an event. For a test \(A\) on the outcomes of \(X\) with \(\P{A(X)}>0,\) the method \(\pr{Condition}\) keeps the outcomes \(x\) for which \(A(x)\) is true; the constructor renormalizes their probabilities.
\begin{algorithm}
\caption{Condition an rv on an event.}
\begin{algorithmic}[1]
\State \textbf{Input:} a test \(A\) on the outcomes of \(X\) with \(\P{A(X)}>0.\)
\State \textbf{Output:} the rv \(X\) conditioned on \(A(X).\)
\Function{RV.Condition}{\(A\)}
\State \(K\gets\pr{Filter}\rb{X.\pr{Keys}\rb{},\, A}\)
\Return \(\cl{RV}\rb{\pr{MakeMap}\rb{K,\, \qb{X(k):k\in K}}}\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def condition(self, A):
K = Filter(self.keys(), A)
return RV(MakeMap(K, [self(k) for k in K]))
RV.condition = condition
R code
Condition <- function(X, A) {
K <- Filter(Keys(X), A)
RV(MakeMap(K, Apply(K, X)))
}
With this class we can study the content of Th. 1.4.1 numerically. In particular, how quickly do the arrival times on the circle converge to the uniform distribution? Recall that
\begin{align*} A_k=(A_{k-1}+X_k)\bmod C. \end{align*}With the operators of the class \(\cl{RV},\) the pseudocode uses the same expression.
In Alg. 1.5.18 we iteratively compute the arrival-time position \(\sum_{i=1}^{n}X_i\bmod C,\) where the \(X_i\) are mutually independent with \(X_i\sim\Unif{\set{-1,0,1}},\) and \(A_0=0.\) We track the positions that occur with the smallest and largest probability. Fig. 1.1 shows the result.
\begin{algorithm}
\caption{Track convergence of the arrival-time distribution on a cycle.}
\begin{algorithmic}[1]
\State \textbf{Input:} cycle length \(C,\) number of iterations \(n,\) and step rv \(X.\)
\State \textbf{Output:} smallest and largest probabilities \(m=\qb{m_1,\ldots,m_n}\) and \(M=\qb{M_1,\ldots,M_n}.\)
\Function{ArrivalConvergence}{\(C,\, n,\, X\)}
\State \(A_0\gets\pr{Constant}\rb{0}\)
\For{\(k=1,\, \ldots,\, n\)}
\State \(A_k\gets(A_{k-1}+X)\bmod C\)
\State \(m_k\gets\pr{Minimum}\rb{\qb{A_k(a):a=0,\, \ldots,\, C-1}}\)
\State \(M_k\gets\pr{Maximum}\rb{\qb{A_k(a):a=0,\, \ldots,\, C-1}}\)
\EndFor
\Return \(m,\,M\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def ArrivalConvergence(C, n, X):
A = Constant(0)
m, M = [None] * n, [None] * n
for k in range(n): # Python lists start at index 0.
A = (A + X) % C
m[k] = Minimum([A(a) for a in range(C)])
M[k] = Maximum([A(a) for a in range(C)])
return m, M
R code
ArrivalConvergence <- function(C, n, X) {
A <- Constant(0)
m <- numeric(n)
M <- numeric(n)
for (k in seq_len(n)) {
A <- (A + X) %% C
m[k] <- Minimum(Apply(0:(C - 1), A))
M[k] <- Maximum(Apply(0:(C - 1), A))
}
list(m, M)
}
Finally, we explain how \(\pr{SearchSorted}\) works. Given a sorted list \(A\) and a number \(x,\) it returns the number of entries of \(A\) that are less than or equal to \(x.\) We first give the algorithm, then provide an example, and finally prove that it returns the stated number.
The algorithm9Like sorting, efficiently searching sorted data is used almost everywhere that computers are used. The ideas behind this algorithm are very important. inspects the middle of the current part of the list and then calls itself on either the left or the right part. Each call therefore reduces the part that remains to be searched by about one half, so only about10\(\log\) is the natural logarithm, \(\log_2\) has base 2. \(\log_2 n\) comparisons are needed for a list of length \(n.\)
\begin{algorithm}
\caption{Find how many entries of a sorted list are \(\leq x.\)}
\begin{algorithmic}[1]
\State \textbf{Input:} a sorted list \(A=\qb{a_1,\, \ldots,\, a_n}\) and a number \(x.\)
\State \textbf{Output:} the number of entries in \(A\) that are less than or equal to \(x.\)
\Function{SearchSorted}{\(A,\, x,\, l=1,\, r=n\)}
\If{\(l>r\)}
\Return \(r\)
\EndIf
\State \(m\gets\lfloor(l+r)/2\rfloor\)
\If{\(x < a_m\)}
\Return \(\pr{SearchSorted}(A,\, x,\, l,\, m-1)\)
\EndIf
\Return \(\pr{SearchSorted}(A,\, x,\, m+1,\, r)\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Python code
def SearchSorted(A, x, l=1, r=None):
# Keep the pseudocode's one-based search bounds; Python indexes from zero.
if r is None:
r = len(A)
if l > r:
return r
m = (l + r) // 2
if x < A[m - 1]:
return SearchSorted(A, x, l, m - 1)
return SearchSorted(A, x, m + 1, r)
R code
SearchSorted <- function(A, x, l = 1, r = length(A)) {
if (l > r) return(r)
m <- floor((l + r) / 2)
if (x < A[[m]]) return(SearchSorted(A, x, l, m - 1))
SearchSorted(A, x, m + 1, r)
}
Consider \(A=\qb{1,2,3}\) and \(x=1.1.\) Initially, \(l=1\) and \(r=3,\) so \(m=2.\) Since \(x<a_2=2,\) the next call searches with \(l=1,\ r=1.\) Now \(m=1.\) Since \(a_1=1\leq x,\) the next call has \(l=2,\ r=1.\) As \(l>r,\) it returns \(r=1:\) exactly one entry is less than or equal to \(1.1.\)
To prove correctness, we keep track of what each recursive call leaves unchanged.11You may skip this proof, but I advise against it: it illustrates one of the most important ideas in reasoning about algorithms. Let \(k\) be the number of entries of \(A\) that are less than or equal to \(x.\)
The first major idea to find a loop invariant.12A loop invariant is a property that holds initially and remains true after each iteration; here, after each recursive call. For this algorithm, this invariant is \(l-1\leq k\leq r.\) It13Note, the loop invariant is not \(l\leq k\leq m\); the \(-1\) is essential. holds initially because \(l=1,\) \(r=n,\) and \(0\leq k\leq n.\) If \(x<a_m,\) sortedness gives \(k\leq m-1,\) so setting \(r=m-1\) preserves the invariant. Otherwise \(k\geq m,\) so setting \(l=m+1\) preserves it.14The key is that with choice, the loop invariant becomes \(m\leq k \leq r\).
Next, we should show that the algorithm terminates in a finite number of steps. Here, each call with \(l\leq r\) strictly reduces the number of indices still to be searched, so the recursion must terminate.
Finally, we need to check what is the terminal value of the algorithm. here, the terminal condition is \(l>r,\) and the loop invariant forces \(k=r=l-1.\) Thus the returned value \(r\) is correct. A bit of thought shows that the cases when no entry or every entry is less than or equal to \(x\) are included as terminal values.
TF 1.
Let \(w\) be the map with \(w(a)=1,\) \(w(b)=2,\) and \(w(c)=7.\) Apply \(\pr{NormalizeMap}(w,\epsilon=0.15).\) Claim: the resulting pmf map \(p\) satisfies \(p(b)=2/9.\)
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. The original relative weights are \(0.1,\) \(0.2,\) and \(0.7,\) so the key \(a\) is removed. The retained weights \(2\) and \(7\) are then normalized by their sum \(9.\)
TF 2.
The function \(\pr{CumSum}\) returns the running totals of a list. Claim:
\begin{equation*} \pr{CumSum}\rb{\qb{3,-1,4,-2}}=\qb{3,2,6,4}. \end{equation*}Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. The successive sums are \(3,\) \(3-1=2,\) \(2+4=6,\) and \(6-2=4.\)
TF 3.
Let \(X\) and \(Y\) be independent rvs. Consider the central part of \(\pr{BinaryTransform}\):
\begin{algorithm}
\begin{algorithmic}[1]
\State \(w\gets\pr{Map}()\)
\For{\(x\in X.\pr{Keys}\rb{}\)}
\For{\(y\in Y.\pr{Keys}\rb{}\)}
\State \(z\gets f(x,\, y)\)
\State \(w(z)\xleftarrow{+}\text{???}\)
\EndFor
\EndFor
\end{algorithmic}
\end{algorithm}
Claim: replacing \(\text{???}\) by \(X(x)\cdot Y(y)\) makes \(\cl{RV}\rb{w}\) the rv \(Z=f(X,Y).\)
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. Independence gives probability \(X(x)\cdot Y(y)\) to the pair \((x,y),\) and all pairs with the same value \(z=f(x,y)\) contribute to the same key.
TF 4.
Let \(X\) be an rv with \(\P{X=-1}=\P{X=1}=1/2.\) Claim: the rvs \(X+X\) and \(2\cdot X\) have the same distribution.
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. The operators of \(\cl{RV}\) treat the two operands as independent rvs. Hence \(X+X\) is the sum of two independent copies of \(X,\) with \(\P{X+X=0}=1/2,\) while \(2\cdot X\) takes the values \(\pm2\) with probability \(1/2\) each.
TF 5.
Let \(A=\qb{a_1,\ldots,a_n}\) be sorted. Consider the recursive function \(\pr{SearchSorted}\):
\begin{algorithm}
\begin{algorithmic}[1]
\Function{SearchSorted}{\(A,\, x,\, l=1,\, r=n\)}
\If{\(l>r\)}
\Return \(r\)
\EndIf
\State \(m\gets\lfloor(l+r)/2\rfloor\)
\If{\(x < a_m\)}
\Return \(\pr{SearchSorted}(A,\, x,\, l,\, m-1)\)
\EndIf
\Return \(\pr{SearchSorted}(A,\, x,\, \text{???},\, r)\)
\EndFunction
\end{algorithmic}
\end{algorithm}
Claim: at \(\text{???},\) the algorithm should have \(m+1.\)
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
True. When \(a_m\leq x,\) the first \(m\) entries are no longer in doubt, so the recursive call searches the part starting at \(m+1.\)
TF 6.
Let the rv \(X\) have cumulative distribution function \(F_X\) and let \(U\sim\text{Unif}(0,1).\) Claim: \(F_{X}(F_{X}^{-1}(U))\sim\text{Unif}(0,1).\)
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False when \(F\) has jumps.
TF 7.
Let \(X\) and \(Y\) be two independent rvs with support \(\set{0, 1, 2, \ldots}.\) Claim:
\begin{equation*} \P{X-Y\le k}=\sum_{i=0}^{\infty}\sum_{i=0}^{\infty}\1{i-j\le k}X(i)\cdot Y(j). \end{equation*}Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. Check the index of the second summation.
TF 8.
The function \(\pr{ToFraction}(x,d)\) first rounds \(x\) to \(d\) decimal places and then reduces the resulting fraction. Claim: \(\pr{ToFraction}(1/3,2)=1/3.\)
Solution
Did you actually try? Write your solution down first for comparison.
Show the solution
False. It first uses denominator \(100\) and numerator \(\operatorname{round}(100/3)=33.\) Since \(33\) and \(100\) have greatest common divisor one, the function returns \(33/100.\)