Real questions rarely involve one event. Will it rain and will the trail flood? Will the first or the second attempt succeed? Two rules handle most of them: "or" adds (carefully), and "and" multiplies, when the events don't affect each other. A tree diagram keeps the bookkeeping straight when they do. The "and" rule has a sobering consequence for AI systems that act in many steps: an agent that gets each step right 95% of the time finishes a ten-step task only about 60% of the time. This lesson builds both rules, draws the trees, checks them by simulation, and works out exactly that.
What you'll be able to do
Find the chance of "A or B": add, then subtract the overlap so it isn't counted twice
Find the chance of "A and B" for independent events by multiplying
Draw a probability tree: multiply down each branch, add the branches that make an event, with and without replacement
Work out how reliable a multi-step agent is when every step can fail, by hand, in a plot and with PyTorch
Quick check
Have a guess before you start. Two fair coins are tossed. What is the chance both land heads?
1/4
1/2
1/3
1
Show the answer
1/4
Half the time the first is heads, and half of those the second is too: 1/2 × 1/2 = 1/4.
The math: "or" adds, "and" multiplies
Purpose. Chances of several things together.
"Or". For a die, P(even or above 4): the outcomes are 2, 4, 5 and 6, so 4/6. Adding P(even) = 3/6 and P(above 4) = 2/6 gives 5/6: too big, because 6 is in both and got counted twice. Subtract the overlap:
P(A or B)=P(A)+P(B)−P(A and B)
In plain words: add the two, then take away what they share, so nothing is counted twice.
When A and B can't happen together (mutually exclusive), the overlap is 0 and the chances simply add.
The picture. Sort the die's six faces into two circles: even on the left, above 4 on the right. The 6 belongs to both, so it sits where the circles overlap. Step through the three pictures and watch which faces each chance counts.
Try it now
Quick check
From lesson 28: if A = {2, 4, 6} and B = {5, 6}, what is A ∩ B?
{2, 4, 5, 6}
{}
{5}
{6}
Show the answer
{6}
The intersection holds what's in both: just 6. That overlap is what "or" must not count twice.
"And", for independent events. Two events are independent when one happening doesn't change the chance of the other: a coin and a die, or two separate coins. Then
P(A and B)=P(A)×P(B)
In plain words: take the share of the first, and of that share, the share where the second also happens.
P(six on a die and heads on a coin) = 1/6 × 1/2 = 1/12.
A tree diagram. Drawing two red cards from a bag of 4 red and 6 black, without putting the first back: the second draw depends on the first. A tree handles it: multiply down each branch, then add the branches you want.
The picture. Read the tree from left to right. From the bag, the first card is red (0.4) or black (0.6). From each of those, two more branches give the second card, with its chances once the first is out: after a red, 3 of the 9 cards left are red. Each step multiplies down one path and writes the result in the box at its end.
Symbols and formula. The general "and" rule uses the chance of the second given the first (lesson 90 builds it properly); for independent events that's just P(B):
P(A and B)=P(A)×P(B∣A)
In plain words: the first, then the second given that the first happened.
Both red without replacement: 0.4 × 3/9 = 0.1333. With replacement, the draws are independent: 0.4 × 0.4 = 0.16. The tree also gives P(second red) = 0.1333 + 0.2667 = 0.4: the same as the first draw, a neat fact about drawing without looking.
Quick check
A die is rolled and a coin is tossed. What is P(even and tails)?
1/4
1
1/12
1/2
Show the answer
1/4
Independent: 3/6 × 1/2 = 1/4.
Quick check
For a die, what is P(less than 3 or even)?
4/6
2/6
3/6
5/6
Show the answer
4/6
2/6 + 3/6 − 1/6 (the 2 is in both) = 4/6: the outcomes 1, 2, 4, 6.
In your own words
In your own words: why does "or" subtract the overlap, while "and" for independent events multiplies?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: simulate, and multiply many chances
Purpose. Check the rules by simulation, and combine many chances at once.
It runs right here in your browser, with nothing to install.
& means "and" element by element. Two simulated coins land on 0.25, matching 1/2 × 1/2. np.prod multiplies every entry of an array, which is exactly what "all of these independent things happen" needs: here four steps with different chances, together 0.6772.
Code flow. A simulation applies the rules one trial at a time. Step through a small one: six rolls of a die and six tosses of a coin (1 is heads), checked trial by trial. In the loop, or lets a trial count for "even or above 4" when either test passes, and and lets it count for "six and heads" only when both do. These are the rules that | and & apply to whole arrays at once (| is "or" element by element, the partner of &).
A named mistake: multiplying dependent events as if independent. Two draws without replacement aren't independent, so 0.4 × 0.4 overstates the chance of two reds; the second factor must be 3/9. The test is to ask: does knowing the first outcome change the chances for the second? If it does, use the tree.
Simulating without replacement. NumPy can draw without putting back: rng.choice(cards, size=2, replace=False) picks two different cards. Repeating it many times and counting the both-red draws gives about 0.133, the tree's answer.
Worked example
Worked example: three hand answers, checked by simulation
Check P(even or above 4) = 4/6, P(six and heads) = 1/12 and P(both red, no replacement) = 2/15 by simulation.
Each simulated share lands within a few thousandths of its exact answer: 0.667, 0.083 and 0.133. The cards are 1 for red and 0 for black; replace=False keeps the second pick from repeating the first card, which is what makes the draws dependent.
All three: 0.9 × 0.8 × 0.5 = 0.36. At least one: 1 − 0.1 × 0.2 × 0.5 = 0.99.
Drill
A tree, checked by simulation
A bag has 3 red and 2 black. Set exact to P(both red) drawing 2 without replacement, rounded to 4 places. Then, with seed 4, draw 2 without replacement 20,000 times and set sim to the share of both-red draws, rounded to 2 places.
In the lesson, your code is checked as you write it.
In your own words
How do you decide whether two events are independent?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: how reliable is a multi-step agent?
Purpose. Small failure rates compound over many steps.
An AI agent carries out a task as a chain of steps: search, read, decide, call a tool, check, and so on. If each step succeeds independently with chance p, the whole n-step task succeeds with
P(all n steps)=pn
In plain words: multiply p by itself once per step.
for n in [5, 10, 20]:
print(n, round(0.95 ** n, 4), round(0.99 ** n, 4))
At 95% per step, a 10-step task succeeds only 60% of the time, and a 20-step one 36%. Raising each step to 99% lifts the 10-step task to 90%. Long chains are only as good as their weakest compounding.
Quick check
Each of 10 steps succeeds with chance 0.95. What is the chance at least one step fails?
About 0.40
0.5
0.95
0.05
Show the answer
About 0.40
P(all succeed) = 0.95¹⁰ ≈ 0.60, so at least one failure has chance 1 − 0.60 ≈ 0.40.
The picture. Plot the chance at 95% per step for every task length from 1 to 30 steps, with the Matplotlib lines from lesson 19:
import matplotlib.pyplot as plt
chance = []
for n inrange(1, 31):
chance.append(0.95 ** n)
plt.plot(range(1, 31), chance)
plt.xlabel("steps in the task")
plt.ylabel("chance every step succeeds")
plt.show()
The curve never reaches 0, but it falls fastest at the start: each step keeps 95% of whatever chance is left, so the early steps take the biggest bites.
Quick check
Read the plot. Where does the curve drop below one half?
It never drops below one half
Between 25 and 30 steps
Between 10 and 15 steps
Before 5 steps
Show the answer
Between 10 and 15 steps
The first cell of this part printed 0.5987 at 10 steps and 0.3585 at 20, and the curve crosses one half between 10 and 15. From there on, a task at 95% per step fails more often than it succeeds.
What engineers do about it. Because reliability compounds, agent builders shorten chains, make each step more reliable, and add checks that catch a failed step and retry it. A retry turns a step that fails 5% of the time into one that fails only when two attempts in a row fail, about 0.25% if the attempts are independent: the "or" rule working in your favor.
The weakest step dominates. Steps rarely share one success rate. A chain of a reliable step (0.99), a shaky one (0.9) and a good one (0.95) succeeds with chance 0.99 × 0.9 × 0.95, about 0.85, and most of the loss comes from the shaky step. Raising it to 0.99 lifts the whole chain to 0.99 × 0.99 × 0.95, about 0.93, while perfecting the 0.99 step would barely move it. Multiplying shows where effort pays. The product has a limit worth saying out loud: it assumes the steps fail independently. If one bad input trips several steps together, failures cluster, and the chain's real record can differ from the product, so engineers measure it end to end as well.
Quick check
What does this print?
chances = [0.99, 0.9, 0.95]
total = 1for c in chances:
total = total * c
print(round(total, 3), round(1 - total, 3))
0.9 0.1
0.154 0.846
2.84 -1.84
0.846 0.154
Show the answer
0.846 0.154
"And" multiplies: 0.99 × 0.9 × 0.95 ≈ 0.846 for the whole chain, so it fails with chance 1 − 0.846 = 0.154.
In PyTorch. The whole table from the first cell of this part takes one line. p holds the two per-step chances as a column and n the three task lengths as a row; p ** n raises every chance to every length by broadcasting (lesson 64), one row per chance and one column per length.
import torch
p = torch.tensor([[0.95], [0.99]]) # a column: each step's chance
n = torch.tensor([5, 10, 20]) # a row: steps in the taskprint(p ** n)
The six numbers are the ones that cell printed: 0.7738, 0.5987 and 0.3585 at 95% per step, then 0.951, 0.9044 and 0.8179 at 99% (PyTorch shows four places, so 0.951 appears as 0.9510). Fed the step rates measured from an agent's logs, the same line gives its chance of finishing tasks of every length.
Drill
Chains and retries
Set rates to the success chance of a 10-step task for per-step chances 0.9, 0.95 and 0.99, rounded to 4 places, as a list. Then set retry to the success chance of one step that gets two independent tries at 0.95 each, and with_retry to the 10-step chance when every step has that retry, rounded to 4 places.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write