Foundations to FrontierPart VII: Applied mathematics and computationBezhig

A03: Probability, random variables, and simulation

5 exercises, each with a complete solution. 1 figure. 1 code listing. 1 note from the engine.

On this page
  1. A. Prerequisites and observable goals
  2. B. The central question: what can be known before an uncertain outcome occurs?
  3. C. Conditioning changes the population under consideration
  4. D. A rare-event calculation with actual counts
  5. E. Random variables turn outcomes into quantities
  6. F. Select distributions by their generating assumptions
  7. G. Independent practice
  8. H. Complete solutions: A03
  9. I. Retention and readiness

A. Prerequisites and observable goals#

Before

Fractions, sets, finite sums, and basic function notation. Integrals from Modules 16–17 support continuous distributions.

After

Compute conditional probabilities without reversing them, distinguish independence from exclusivity, derive expectations and variances, and choose a probability model from assumptions rather than appearance.

Level: Degree core.

B. The central question: what can be known before an uncertain outcome occurs?#

A probability model consists of a sample space of possible outcomes, events that are subsets of that space, and a probability assignment. Probability is not a synonym for a personal feeling of confidence: calculations are conditional on the specified model. A fair six-sided die has six equally probable elementary outcomes; a production server’s next latency need not have equally likely values, independence across requests, or an unchanging distribution.

For an event AA, 0≤P(A)≤10\le P(A)\le1, and the whole sample space has probability one. For disjoint events, probabilities add. General addition requires subtracting overlap:

P(A∪B)=P(A)+P(B)−P(A∩B).P(A\cup B)=P(A)+P(B)-P(A\cap B).

A count divided by a total gives a probability only when the counted elementary outcomes are equally probable. Ordered outcomes and unordered selections are different sample spaces. For example, selecting two distinct items from five gives 5⋅4=205\cdot4=20 ordered pairs but (52)=10\binom52=10 unordered pairs. Each unordered pair corresponds to two orders. Counting foundations are developed further in C05; probability uses those counts only under a justified sampling rule.

C. Conditioning changes the population under consideration#

For P(B)>0P(B)>0,

P(A∣B)=P(A∩B)P(B).P(A\mid B)=\frac{P(A\cap B)}{P(B)}.

The vertical bar means “within outcomes where BB occurred.” It does not reverse the direction of a causal relationship. Events are independent when P(A∩B)=P(A)P(B)P(A\cap B)=P(A)P(B). For positive P(B)P(B), this is equivalent to P(A∣B)=P(A)P(A\mid B)=P(A). Disjoint events with positive probabilities are not independent: learning that one occurred rules out the other.

Bayes’ theorem rearranges the same joint probability:

P(A∣B)=P(B∣A)P(A)P(B).P(A\mid B)=\frac{P(B\mid A)P(A)}{P(B)}.

If AA and AcA^c partition the possibilities, then P(B)=P(B∣A)P(A)+P(B∣Ac)P(Ac)P(B)=P(B\mid A)P(A)+P(B\mid A^c)P(A^c). This denominator accounts for every route to observing BB, including false alarms. A system’s sensitivity is not the probability that a flagged case is genuine.

D. A rare-event calculation with actual counts#

Suppose 1% of requests are genuinely defective, a detector flags 90% of defective requests, and it falsely flags 5% of nondefective requests. In a model population of 10,000 requests, expect 100 defective requests, 90 true flags, and 0.05(9900)=4950.05(9900)=495 false flags. Among 585 total flags, only 90 are genuine:

P(defective∣flag)=90585=213≈0.154.P(\text{defective}\mid\text{flag})=\frac{90}{585}=\frac2{13}\approx0.154.

This does not make the detector useless. It shows why its operating threshold, base rate, and cost of false positives matter. A different population with a higher defect rate changes the posterior even when sensitivity and false-positive rate remain the same. The numerical result is conditional on those assumptions; it is not an empirical claim about a real system.

Counts make the rare-event calculation visible. Of 10,000 requests, 100 are defective and the detector flags 90 of them; of the 9,900 others it falsely flags 495. The bar shows the 585 flags to scale: only 90 are genuine, about 15.4 percent.

E. Random variables turn outcomes into quantities#

A random variable XX is a function from outcomes to numbers. For a discrete variable, its mass function is p(x)=P(X=x)p(x)=P(X=x) and

E[X]=∑xxp(x),Var⁡(X)=E[(X−E[X])2]=E[X2]−E[X]2.E[X]=\sum_x x p(x),\qquad \operatorname{Var}(X)=E[(X-E[X])^2]=E[X^2]-E[X]^2.

Expectation is a probability-weighted average, not necessarily a possible observed value. Variance has squared units; standard deviation has the original units. For a continuous density ff, probabilities are integrals over intervals, and E[X]=∫xf(x) dxE[X]=\int x f(x)\dd x when the expectation is well-defined. A density can exceed one over a short interval; its integral over the whole domain must equal one. A continuous variable’s probability at a single point is zero even when that point lies in its support.

Linearity of expectation does not require independence: E[X+Y]=E[X]+E[Y]E[X+Y]=E[X]+E[Y] when the expectations exist. Variance does require attention to dependence:

Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)+2Cov⁡(X,Y).\operatorname{Var}(X+Y)=\operatorname{Var}(X)+\operatorname{Var}(Y)+2\operatorname{Cov}(X,Y).

Independence implies zero covariance when the relevant moments exist, but zero covariance does not generally imply independence. Shared server congestion can make two request latencies positively dependent, increasing the variability of their sum.

An indicator IAI_A equals 1 if AA occurs and 0 otherwise. Then E[IA]=P(A)E[I_A]=P(A). A binomial count X=I1+⋯+InX=I_1+\cdots+I_n for independent, identical Bernoulli trials has mean npnp and variance np(1−p)np(1-p). The derivation exposes exactly where identical probabilities and independence enter; it is more useful than remembering a distribution name.

F. Select distributions by their generating assumptions#

ModelInterpretation and conditionsMean; variance
Bernoulli(p)(p)One event, coded 0 or 1pp; p(1−p)p(1-p)
Binomial(n,p)(n,p)Count in nn independent identical trialsnpnp; np(1−p)np(1-p)
Geometric(p)(p)Number of independent trials through first success; starts at 11/p1/p; (1−p)/p2(1-p)/p^2
Poisson(λ)(\lambda)Count in a model interval with specified intensity and suitable independent-increment assumptionsλ\lambda; λ\lambda
Uniform(a,b)(a,b)Constant density on a finite interval, a<ba<b(a+b)/2(a+b)/2; (b−a)2/12(b-a)^2/12
Exponential(λ)(\lambda)Waiting time in a constant-rate memoryless model, λ>0\lambda>01/λ1/\lambda; 1/λ21/\lambda^2
Normal(μ,σ2)(\mu,\sigma^2)Symmetric continuous model; often an approximation, not a law of all noiseμ\mu; σ2\sigma^2

A normal model permits negative values, so applying it to latency requires a justified approximation over the relevant range. An exponential model’s memorylessness is a substantive assumption, not a property of every wait. Fit and validate a model against the mechanism and observations; do not choose it only because its formula is convenient. [PROB]

For a synthetic latency XX equal to 10 ms with probability 0.95 and 110 ms with probability 0.05, E[X]=15E[X]=15 ms. But 15 ms is never observed. Its variance is 0.95(102)+0.05(1102)−152=475 ms20.95(10^2)+0.05(110^2)-15^2=475\ \mathrm{ms}^2. The average hides the 110 ms tail. A capacity or responsiveness requirement needs appropriate tail behavior as well as a mean.

G. Independent practice#

F foundation C standard course work T transfer S optional stretch L runnable lab or project. Attempt the complete set before opening its solutions.

A03.01FSolution

A uniformly selected unordered pair comes from five distinct items. What is the probability that a particular item is included? Derive the result by counting, not by assuming the two selections are independent.

A03.02CSolution

Recompute the detector posterior when the defect rate is 10%, sensitivity remains 90%, and false-positive rate remains 5%. Explain why the posterior changes.

A03.03CSolution

For the two-point latency model above, compute the expectation and variance of the sum of two independent latencies. Then explain which calculation survives if independence is removed and which additional quantity the variance needs.

A03.04TSolution

Let XX be uniform on {−1,0,1}\{-1,0,1\} and Y=X2Y=X^2. Show that their covariance is zero but they are not independent. Explain why “uncorrelated” is a weaker statement.

A03.05LabSolution

Implement the seeded binomial experiment in probability_lab.py. Generate independent pseudo-random Bernoulli trials, group them into counts, and compare the sample mean and variance with npnp and np(1−p)np(1-p). Validate nn, pp, and the number of repetitions. Record the seed and explain why a close sample result is not a proof of the formulas.

Optional small hints

A03.01: count pairs containing the chosen item. A03.04: compute E[XY]=E[X3]E[XY]=E[X^3]. A03.05: derive the expected quantities analytically before generating any samples.

H. Complete solutions: A03#

Compare the first step where your work differs. A corrected answer is not yet an independent success.

A03.01Show solution

Count the relevant sample space

There are (52)=10\binom52=10 equally likely unordered pairs. Exactly four include the specified item, one for each possible partner. The probability is 4/10=2/54/10=2/5. The selections without replacement are dependent, but the combinatorial model already accounts for that. Summing five inclusion indicators gives exactly two for every pair; symmetry provides the independent check 5p=25p=2.

Back to A03.01
A03.02Show solution

The base rate changes the mixture

The joint probability of a genuine flag is 0.9(0.1)=0.090.9(0.1)=0.09. The false-flag probability is 0.05(0.9)=0.0450.05(0.9)=0.045. Thus the posterior is 0.09/(0.09+0.045)=2/30.09/(0.09+0.045)=2/3. The detector’s conditional operating rates are unchanged, but a greater fraction of requests belongs to the defective population. The observed flags therefore contain a larger fraction of genuine cases. Conditioning cannot ignore population composition.

Back to A03.02
A03.03Show solution

Means add more generally than variances

The expected sum is 15+15=3015+15=30 ms. Under independence, the variance is 475+475=950 ms2475+475=950\ \mathrm{ms}^2. Without independence the expectation remains 30 ms because linearity does not require it. The variance becomes 950+2Cov⁡(X1,X2)950+2\operatorname{Cov}(X_1,X_2) in squared milliseconds. A shared slow state could make the covariance positive; negative dependence could reduce it. Do not add standard deviations as though they were variances.

Back to A03.03
A03.04Show solution

Dependence can be nonlinear

E[X]=0E[X]=0, E[Y]=2/3E[Y]=2/3, and E[XY]=E[X3]=0E[XY]=E[X^3]=0. Hence covariance is 0−0(2/3)=00-0(2/3)=0. Yet P(Y=0∣X=0)=1P(Y=0\mid X=0)=1, whereas P(Y=0)=1/3P(Y=0)=1/3. Therefore XX and YY are dependent. Covariance detects a particular linear association, not every functional dependence. Here YY is completely determined by XX.

Back to A03.04
A03.05Show solution

Reference experiment

code/solutions/probability_lab.pyPython
"""A03.05: seeded binomial experiment with analytic comparison."""
import random
import statistics

def binomial_experiment(n: int = 10, p: float = 0.3,
                        trials: int = 10000, seed: int = 41) -> dict:
    if type(n) is not int or n < 0 or not 0 <= p <= 1:
        raise ValueError("invalid binomial parameters")
    if type(trials) is not int or trials < 2:
        raise ValueError("at least two trials required")
    rng = random.Random(seed)
    data = [sum(rng.random() < p for _ in range(n)) for _ in range(trials)]
    return {"sample_mean": statistics.mean(data),
            "sample_variance": statistics.variance(data),
            "theory_mean": n * p, "theory_variance": n * p * (1 - p),
            "trials": trials, "seed": seed}

if __name__ == "__main__":
    print(binomial_experiment())

Each uniform pseudo-random draw is compared with pp to form an indicator. The sum of nn such indicators is one binomial-model observation. The sample variance uses a denominator of trials minus one, which estimates population variance under the independent sampling model. For the default n=10,p=0.3n=10,p=0.3, the analytical targets are 3 and 2.1. The stored seed makes this particular algorithm and environment reproducible, not cryptographically unpredictable. Sampling variation remains even with correct code. A seeded experiment is a check on the implementation and a lesson in variability, while the indicator derivation establishes the theoretical moments under the model assumptions.

Back to A03.05

I. Retention and readiness#

Retrieve fractions, inclusion–exclusion, and the difference between a density and an area. Advance when you can name the conditioning population, reject independence when evidence does not support it, and explain a mean that is never itself observed.