Inside a computer, every number is a row of tiny switches, each on or off. How many switches a number gets decides how big it can be and how exact. That's why 0.1 + 0.2 isn't quite 0.3, why a model's memory is its number of weights times 4 bytes, and why engineers run models in "half precision" or squeeze them into 8 bits. This lesson opens the box: counting in twos, then floats, then what it all costs a model.
What you'll be able to do
Read and write whole numbers in base 2, and say how many values n bits can hold (2ⁿ)
Explain a float as a sign, a power of two and a fixed number of binary digits, and why that limits precision
Use bin() and int(text, 2) in Python, and see why testing floats with == goes wrong
Work out a model's memory from its count of numbers and the bytes each takes, and the error 8-bit rounding adds
Quick check
Have a guess before you start. A byte is 8 switches in a row, each on or off. How many different on-off patterns can it show?
256
16
8
255
Show the answer
256
One switch gives 2 patterns. Each switch you add doubles them, because every old pattern can go on with the new switch on or off: 2 × 2 × 2 × 2 × 2 × 2 × 2 × 2 = 256.
The math: counting in twos
Purpose. Write numbers with only two digits, 0 and 1, and see what a fixed number of them can hold.
In base ten, from lesson 1, each place is worth ten times the place on its right: ones, tens, hundreds. Base two works the same way with twos. Each place is worth twice the place on its right: 1, 2, 4, 8, 16 and so on, the powers of two from lesson 10. Its only digits are 0 and 1, so each place is either used or not. A binary digit is called a bit.
11012=1×8+1×4+0×2+1×1=13
In plain words: label the places from the right 1, 2, 4, 8. Add up the worth of every place that holds a 1. The small 2 says the digits are in base 2.
Quick check
From an earlier lesson: in 4,072, what is the 7 worth?
70
7,000
700
7
Show the answer
70
The 7 sits in the tens place, so it's worth 7 × 10 = 70. Base 2 reads places the same way, with 1, 2, 4, 8 where base ten has 1, 10, 100, 1,000.
From a number to bits. To write 13 in base 2, start at the biggest place that fits, 8, and work down. Each place gets a 1 if its worth fits into what's left, and a 0 if it doesn't; a 1 takes that worth out. The picture shows 13 as squares: each step pulls a row of 8, 4, 2 or 1 out of what's left, and the strip on top fills in that place's bit.
Try it now
Then type 200 in the number box and press Use these numbers: 200 needs eight places, a whole byte.
How much n bits can hold. One bit has two patterns, 0 and 1. Two bits have four: 00, 01, 10 and 11. Every bit you add doubles the count, because each old pattern can carry on with a 0 or with a 1.
values in n bits=2nlargest whole number=2n−1
In plain words: n bits make 2ⁿ patterns. Counting from 0, the biggest number they can write is one less.
Eight bits make a byte: 2⁸ = 256 patterns, the whole numbers 0 to 255. Computer memory is counted in bytes, and the prefixes from lesson 11 scale them: a megabyte is 10⁶ bytes, and a gigabyte is 10⁹.
Quick check
How many different values can 4 bits hold?
4
16
8
15
Show the answer
16
2⁴ = 2 × 2 × 2 × 2 = 16 patterns, from 0000 to 1111: the numbers 0 to 15.
Floats: scientific notation in base 2. Whole numbers are simple: bits in places. A number like 3.75 or 0.1 is stored as a float, short for floating point. It's the scientific notation of lesson 11, with 2 in place of 10:
x=±1.d1d2d3…×2k
In plain words: a sign, a power of two, and a fixed number of binary digits starting with 1. The power says where the point really goes, so the point "floats".
After the point, base 2 places keep halving: ½, ¼, ⅛. So 3.75 = 2 + 1 + ½ + ¼ is 11.11 in base 2. Moving the point one place left halves it, and × 2¹ doubles it back: 3.75 = 1.111 × 2¹. Check it: 1.111 in base 2 is 1 + ½ + ¼ + ⅛ = 1.875, and 1.875 × 2 = 3.75.
A float32 spends its 32 bits as 1 for the sign, 8 for the power and 23 for the digits after the point. The leading 1 is always there, so it isn't stored, and float32 keeps 24 digits in all. A float16 has 1, 5 and 10 bits, so it keeps 11 digits. The picture draws both at the same scale.
Why 0.1 can't be stored exactly. In base ten, 1/3 never ends: 0.333… In base two, 1/10 never ends either. Doubling moves the point one place right, so each doubling brings the next digit in front of the point. Double 0.1 again and again: 0.2, 0.4 and 0.8 stay under 1, so the digits are 0, 0, 0. Then 1.6 passes 1: a digit 1, and taking the 1 off leaves 0.6. That doubles to 1.2: another 1, leaving 0.2, the value after the first doubling. So the same digits come round forever: 0.1 is 0.000110011001100… in base 2, with 0011 repeating. A float keeps only its 24 or 11 digits and rounds off the rest, so the stored 0.1 is a hair off. That's the crumb behind 0.1 + 0.2 in lesson 7.
Fixed digits, fixed precision. 24 binary digits are worth about 7 decimal digits, and 11 are worth about 3. Whole numbers are exact only while they fit in the digits: float32 holds every whole number up to 2²⁴ = 16,777,216, and float16 only up to 2¹¹ = 2,048. Past that, neighboring floats are more than 1 apart. The Python part checks each of these numbers.
Quick check
Why can't a float store 0.1 exactly?
Its base 2 digits never end
Its sign bit gets in the way
Floats hold whole numbers only
0.1 is too small for 32 bits
Show the answer
Its base 2 digits never end
1/10 in base 2 is 0.000110011…, with 0011 repeating forever, like 1/3 in base ten. A float keeps a fixed number of digits, so it rounds, and the stored value is a hair off 0.1.
Quick check
float32 keeps 24 binary digits. Which is the first whole number it can't hold exactly?
2³² + 1
2²⁴
2²⁴ + 1
2²³ + 1
Show the answer
2²⁴ + 1
2²⁴ is a 1 followed by 24 zeros: one digit times a power of two, so it fits. 2²⁴ + 1 is a 1, 23 zeros and a 1, which is 25 digits, one too many, so it's rounded to a neighbor.
In your own words
In your own words: why does each extra bit double how many values fit, and what does a float's fixed number of digits cost it?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: bits, and the crumbs in a float
Purpose. Ask Python for any number's bits, and watch a float's rounding happen.
bin(n) writes a whole number in base 2, and int(text, 2) reads text in base 2 back into a number. The 2 says which base the text is in:
It runs right here in your browser, with nothing to install.
The answer from bin is text that starts with 0b, Python's mark for "the digits that follow are in base 2". int reads the 0b too, so int(bin(13), 2) gives back 13. The last line is a byte: 256 patterns, the largest 255.
Quick check
What does this print?
print(bin(6), int("110", 2) + 1)
110 7
0b011 7
0b110 111
0b110 7
Show the answer
0b110 7
6 = 4 + 2, so bin(6) is 0b110. int("110", 2) reads the same bits back as 6, and adding 1 gives 7.
Floats, close up. Python's own floats are float64: 64 bits, with 53 binary digits. Print 0.1 to 20 decimal places, with the f-string format from lesson 7, and the crumb shows. The other lines check the math part's numbers: 3.75 as 11.11 and as 1.111 × 2¹, the whole-number edges of float32 and float16, and what 24 and 11 binary digits are worth in decimal digits.
The stored 0.1 is 0.10000000000000000555, a hair over. Both ways of writing 3.75 add up. 2²⁴ = 16,777,216 and 2¹¹ = 2,048 are the edges. And log10 says 2²⁴ is about 10⁷·², so 24 binary digits are worth about 7.2 decimal digits, and 11 about 3.3.
Adding 0.1 ten times. In lesson 19 you'll repeat a line with a loop. For now, ten plus signs do the same job:
Ten tenths should make 1, but each add rounds to the nearest float, and the crumbs pile up. Step through the same adds one at a time, and watch the box for total.
A named mistake: testing floats with ==. You met math.isclose in lesson 7. Now you can see why == fails, and that it fails both ways. It says False for sums that should match. And past 2⁵³, where Python's floats run out of digits, it says True for numbers that differ:
Both tests with a tolerance say True. The last line says True as well, and it's wrong: 2⁵³ + 1 needs 54 digits, so Python rounds it back to 2⁵³. Compare floats with a tolerance. Keep counts as whole numbers (ints, with no point), which Python stores exactly at any size.
Quick check
What does this print?
print(0.5 + 0.25 == 0.75)
False
True
0.75
0.7500000000000001
Show the answer
True
0.5 is 1/2 and 0.25 is 1/4: in base 2 they're 0.1 and 0.01, with nothing cut off. Their sum, 0.11 in base 2, is exactly 0.75, so == says True. Only numbers whose digits run on, like 0.1, get rounded.
The biggest whole number a float holds exactly. A float keeps every whole number exactly until the numbers need more digits than it has. To find the edge, search through powers of two: add 1, take the power away again, and see whether the 1 survived.
At 2²⁰ the 1 still counts; at 2⁶⁰ it's lost. The edge for Python's floats is somewhere between, and the drill at the end of this part has you find it. PyTorch, the library most models are built with, stores numbers as float32 unless asked otherwise. Here float32 is asked to store 2²³ + 1 and 2²⁴ + 1, one power below its edge and one at it:
Worked example
Worked example: how many bits for a vocabulary?
A language model gives every word piece it knows a number. With 50,000 word pieces, how many bits does each number need, and how many bytes?
15 bits make 32,768 values, too few for 50,000. 16 bits make 65,536, enough. bin agrees: after the 0b, 0b1100001101010000 has 16 digits. 16 bits are 2 bytes, so each word piece's number fits in 2 bytes.
Drill
Search for the edge
Find the edge for Python's own floats. Change n until it's the first power where adding 1 to 2.0 ** n is lost (the tests say whether you're too low or too high). Then set edge to 2 ** n, that power of two as a whole number: the largest whole number up to which Python's floats miss none.
n = 20
lost = 2.0 ** n + 1 == 2.0 ** n
print(n, lost)
edge = 0print(edge)
In the lesson, your code is checked as you write it.
In your own words
Why can == say True for two different whole numbers, and False for ten 0.1s added up and 1.0?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: memory, half precision and 8 bits
Purpose. A model's weights are floats. The bytes each one gets set how much memory the model takes and how exact its math is.
Memory is count × bytes.
memory=count of numbers×bytes per number
In plain words: count the numbers, and give each one its bytes: 4 in float32, 2 in float16, 1 in 8 bits.
In lesson 11 every number took 4 bytes. Those were float32's 32 bits, and now the bytes can change. The trail club's sign reader looks at 5 × 5 signs, as in lesson 1: 25 numbers each. A small language model has about 120 million weights. Here's the memory for 1,000 signs, and for that model at 4, 2 and 1 byte per weight:
signs = 1000 * 5 * 5print(signs * 4, "bytes for 1000 signs in float32")
weights = 120e6print(weights * 4 / 1e6, "MB in float32")
print(weights * 2 / 1e6, "MB in float16")
print(weights * 1 / 1e6, "MB in 8 bits")
Halving the bytes halves the memory: 480 MB, then 240, then 120. That's why big models are often run in 16-bit floats, and squeezed into 8 bits when memory is tight.
Quick check
What does this print?
weights = 3e9print(weights * 2 / 1e9)
3.0
6.0
6
12.0
Show the answer
6.0
3 × 10⁹ weights × 2 bytes = 6 × 10⁹ bytes, and dividing by 10⁹ gives 6 gigabytes. It's a float, so 6.0.
In the real tools. PyTorch keeps a tensor's number type in x.dtype, and .to(torch.float16) makes a half-precision copy. Here are 1,000 copies of 0.1, stored both ways, with their memory and the first number as stored:
Rounding weights to 8 bits. Squeezing a model into 8 bits is called quantizing. 8 bits give 2⁸ = 256 levels. Cut the range from the smallest weight to the largest into 255 equal steps (256 levels have 255 gaps between them), and round each weight to the nearest level. Say the sign reader's weights run from −0.66 to 0.91, and round the weight 0.42:
lo = -0.66
hi = 0.91
step = (hi - lo) / 255
w = 0.42
level = round((w - lo) / step)
back = lo + level * step
print(step)
print(level, back)
print(abs(w - back), step / 2)
The weight is stored as level 175, in one byte, and read back as 0.4175, off by 0.0025. Rounding to the nearest level is never off by more than half a step, 0.0031 here, so the error is small and known before you start.
Drill
Round a weight to 8 bits
Another layer's weights run from −0.5 to 0.7. Fix the starter so step is the gap between the 256 levels, level is the weight 0.345 rounded to the nearest level, back is that level read back as a weight, and err is the size of the miss. Each line from step on has a slip.
lo = -0.5
hi = 0.7
step = (hi - lo) / 256
w = 0.345
level = (w - lo) / step
back = level * step
err = w - back
print(step, level, back, err)
In the lesson, your code is checked as you write it.
In your own words
When would you store a model in float16 or 8 bits instead of float32, and what do you give up?
Write a sentence or two, then compare it with a good answer in the lesson.
Goes deeper in
Quantization: storing a real model's weights in fewer bits, and measuring what it costs.
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