Amounts between whole numbers are everywhere: half a trail, a third of the snacks. In AI they're everywhere too. A model's accuracy is a fraction. So is the share of each kind of picture in a data set. This lesson shows what a fraction means, why two fractions can look different and be equal, and how to add them. The one rule to remember: you can only add pieces of the same size.
What you'll be able to do
Read a fraction as pieces taken out of pieces cut, and find equal fractions
Simplify a fraction, and add or subtract fractions by cutting them to the same size first
Check fraction sums exactly in Python with Fraction
Work out a model's accuracy and a data set's class shares as fractions
Quick check
Have a guess before you start. What is 1/2 + 1/3?
2/6
1/6
5/6
2/5
Show the answer
5/6
Half a bar plus a third of a bar is 5/6 of a bar. Adding the tops and the bottoms, 2/5, is the most common slip: it's less than the half you started with. By the end of this lesson you'll see why the answer is 5/6.
The math: equal parts, and adding them
Purpose. A whole number counts whole things. A fraction counts parts of one thing.
Picture a trail bar cut into 4 equal pieces. You eat 3 of them. You've eaten 3/4 of the bar: 3 pieces taken, out of 4 pieces cut.
The bottom number, the denominator, says how many equal pieces the whole was cut into.
The top number, the numerator, says how many of those pieces you have.
Now cut the same bar into 8 pieces instead, and take 6. You've eaten exactly the same amount of bar. So 3/4 and 6/8 are equal fractions: different cuts, same amount.
The picture. A fraction is also a point on a number line. Below, the line from 0 to 1 is the bar laid flat. First it's cut into quarters, and three of them take you to 3/4. Press Next to cut the same line into eighths.
Try it now
You get an equal fraction whenever you multiply (or divide) the top and the bottom by the same number. Each piece gets smaller, and there are more of them, so the amount stays put: the point on the line doesn't move.
Adding has one rule: the pieces must be the same size. A half and a third are different-sized pieces, so you can't just count them together. Watch what happens to the bars below, and to the same two amounts as points on the number line above them. Re-cutting never moves a point; it only renames it. Then the first amount is laid out from 0, and the second is laid on after it.
Symbols and formula. Re-cutting is the trick. To add ba+dc, cut both into b×d pieces. The first becomes a×d pieces of that size, the second c×b:
ba+dc=b×da×d+c×b
In plain words: give both fractions the same bottom number, then add the tops. Keep the bottom.
Worked example:41+32. Cut into 12ths: 1/4 is 3 twelfths and 2/3 is 8 twelfths. So the sum is 11/12.
Subtracting works the same way: same bottom, then subtract the tops.
When a top and bottom share a factor, divide it out to simplify: 6/8 becomes 3/4. Any common bottom works for adding. The smallest one keeps the numbers small, but you can always simplify at the end.
Quick check
Which fraction is equal to 2/3?
3/2
4/5
2/6
8/12
Show the answer
8/12
Multiply the top and the bottom of 2/3 by 4: 8/12. The pieces are a quarter of the size, and there are four times as many, so the amount is the same.
Which is bigger? With the same bottom, the pieces are the same size, so the bigger top wins: 5/8 is more than 3/8. With different bottoms, re-cut first. Is 2/3 more than 3/5? In fifteenths, 2/3 is 10/15 and 3/5 is 9/15, so yes, by one fifteenth.
Watch out for one trap: a bigger bottom means smaller pieces. 1/8 of a bar is less than 1/4 of it, even though 8 is more than 4. The bottom number counts how many pieces the bar was cut into, and more pieces means each one is smaller.
Quick check
What is 3/8 + 1/4?
4/8
3/32
5/8
4/12
Show the answer
5/8
1/4 is 2/8, so 3/8 + 2/8 = 5/8. Re-cut to the same size, then add the tops.
In your own words
In your own words: why can't you add 1/2 and 1/3 by adding the tops and the bottoms?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: fractions that stay exact
Purpose. By hand is fine for a few fractions. Python can check your answers, and do thousands at once.
First, the formula written out with the operators you already know. To add 2/3 and 1/4, cut both into 3 × 4 = 12ths:
a = 2# 2/3 is a over b
b = 3
c = 1# 1/4 is c over d
d = 4
top = a * d + c * b
bottom = b * d
print(f"{a}/{b} + {c}/{d} = {top}/{bottom}")
It runs right here in your browser, with nothing to install.
That's the formula from part 1, line for line. Python also has a ready-made Fraction type that keeps fractions exact and simplifies for you. To use it, you import it: you ask Python to load a tool that ships with it but isn't switched on by default.
from fractions import Fraction
print(Fraction(2, 3) + Fraction(1, 4))
print(Fraction(6, 8)) # simplified as soon as it's madeprint(Fraction(5, 6) - Fraction(1, 4))
Fraction(2, 3) means 2/3: the top first, then the bottom.
Code flow. Here is a Fraction add one line at a time, on the flow's own numbers, 1/2 and 1/3. Each variable shows the Fraction it holds. Watch same as it's made: it's given 3/6.
Two mistakes to know before you meet them. If you forget the import line, Python stops with NameError: name 'Fraction' is not defined: it doesn't know the word yet. And Fraction(3/4) isn't the same as Fraction(3, 4). With a slash, Python works out 3 ÷ 4 = 0.75 first, as a decimal, and Fraction gets a decimal it can't always turn back into a tidy fraction. Give it the top and the bottom as two separate numbers, with a comma.
from fractions import Fraction
print(Fraction(3, 4)) # three quarters, exactlyprint(Fraction(1, 3) + Fraction(1, 3) + Fraction(1, 3)) # exactly 1
The last line shows why exact fractions are worth having: three thirds make exactly one whole, with nothing lost.
Worked example
Worked example: simplifying by hand, checked by Fraction
Simplify 18/24 the way you would on paper, by dividing out the biggest number that goes into both, then check against Fraction.
import math
from fractions import Fraction
top = 18
bottom = 24
common = math.gcd(top, bottom) # the greatest common divisor: 6print("divide both by", common)
print(f"{top}/{bottom} = {top // common}/{bottom // common}")
print("Fraction agrees:", Fraction(top, bottom))
In the lesson you can change this and run it.
math.gcd finds the greatest common divisor: the biggest whole number that divides both. For 18 and 24 that's 6. Dividing the top and the bottom by it gives the simplest form in one step, 3/4. We use // because the result must be a whole number of pieces. The last line shows Fraction reached the same answer by itself.
Quick check
What does this print?
from fractions import Fraction
print(Fraction(3, 8) + Fraction(1, 8))
4/8
1/2
4/16
0.5
Show the answer
1/2
3/8 + 1/8 = 4/8, and Fraction always shows the simplest form: 1/2.
Quick check
In the first cell, which line does the re-cutting: turning both fractions into twelfths?
a = 2
b = 3
c = 1
d = 4
top = a * d + c * b
bottom = b * d
print(f"{a}/{b} + {c}/{d} = {top}/{bottom}")
The lines that set c and d
The line that prints the answer
The lines that set top and bottom
The lines that set a and b
Show the answer
The lines that set top and bottom
Multiplying a by d and c by b gives each fraction's pieces in twelfths; b * d is the new size. The first two lines only store the numbers, and the print only shows them.
Drill
Add two fractions by the formula
Set top and bottom to 3/10 + 2/5 using the formula a * d + c * b over b * d. Then set simple to the same sum as a Fraction, so you can see it simplified.
from fractions import Fraction
a = 3# 3/10
b = 10
c = 2# 2/5
d = 5
top = a + c
bottom = b + d
simple = Fraction(1, 1)
print(f"{top}/{bottom}", simple)
In the lesson, your code is checked as you write it.
In your own words
When would you use the written-out formula, and when Fraction?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: accuracy is a fraction
Purpose. The trail club is teaching a model to read trail signs: arrows, tents and water drops. Every report about that model is full of fractions.
The first fraction is accuracy: of all the signs the model was shown, the share it got right.
accuracy=totalcorrect
In plain words: accuracy is a fraction. Its top is the signs read right, its bottom all the signs shown.
The picture. The club's newest test shows the model 50 signs. Each square below is one sign, filled if the model read it right. Count the empty ones, then press Next to see the accuracy as a bar.
A second fraction comes from the first. The error rate is the share the model got wrong. Right and wrong together make every sign, the whole, so the error rate is what's left of 1 after the accuracy:
That's a fraction subtraction, the same as 10/10 − 9/10. A model that reads 9 signs in 10 right gets 1 in 10 wrong.
The third is the class share: what fraction of the data set each kind of sign makes up. The shares cut one whole, the data set, so they must add up to exactly 1.
Exact fractions matter here. If shares were rounded, they could add to 0.99 or 1.01, and a check that they cover the whole data set would fail for no real reason. You'll meet that rounding problem in the decimals lesson.
Quick check
An older test had 60 signs, and the model read 45 of them right. What does this print?
from fractions import Fraction
correct = 45
total = 60print(Fraction(correct, total))
15/60
3/4
45/60
0.75
Show the answer
3/4
45/60 simplifies by 15 to 3/4: on a test of 60 signs, 45 right is three signs in every four.
In the real tools. In PyTorch, the library most models are built with, a test's right answers and the model's guesses sit in two tensors, lists of numbers that PyTorch works on all at once. Here is the test from the picture: every sign's right answer is 0 (say, an arrow), and the model answers 0 for the first 45 signs and 1 for the last 5.
Quick check
Model A reads 3/4 of the signs right. Model B reads 26/35 right. To see which is higher, what's the first step?
Compare the tops: 26 is more than 3
Compare the bottoms: 35 is more than 4
Add them and check if the sum is over 1
Re-cut both to 140ths, then compare tops
Show the answer
Re-cut both to 140ths, then compare tops
In 140ths, 3/4 = 105/140 and 26/35 = 104/140. With the same bottom the pieces are the same size, so the bigger top wins: model A, by 1/140. The tops and bottoms alone say nothing, because the pieces differ.
Drill
Which model is more accurate?
Model A read 39 of 48 signs right; model B read 52 of 65. B got more signs right, but on a bigger test. Set acc_a and acc_b to their accuracies as Fractions, gap to acc_a - acc_b, and a_wins to whether A is strictly higher (a comparison gives True or False).
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