Arithmetic
How does a machine with finitely many bits add, multiply and divide, and when is its answer wrong?
The part opens with numbers that ran out: YouTube's 32-bit view counter, the Boeing 787's 248-day generator bug, and 0.1 + 0.2. Integers live on a clock of 2^n positions, and two's complement is a relabelling of that clock, so one adder serves signed and unsigned numbers. The ripple-carry adder is proved correct by induction and timed at 2n + 1 gate delays; seeing a block of bits as a function of its carry-in makes the carry operator associative, and the Kogge-Stone tree adds 64 bits in 15 delays. Multipliers become trees of carry-save adders, and division hides a table: emptying five cells of the series' SRT table reproduces the Pentium FDIV bug in miniature. Pebble's ALU is assembled and verified. Then the reals: fixed point, IEEE 754 with its doubling gaps, the rounding model, cancellation, Kahan's summation, the Patriot clock and Ariane 5, and Wilkinson's polynomial, whose roots fly apart when one coefficient moves by 2^-23. It ends with what is still open: how fast multiplication can be, and correctly rounded sin, exp and log.
What you need. Gates, the critical path and induction from Parts 2 and 3. Newton's method is derived where it is used.
- Mathematics, ideas and history
- two's complement as ℤ/2ⁿ, carry-lookahead as parallel prefix, Wallace trees, SRT and Newton division, IEEE 754, error analysis, CORDIC
- What we build or compute
- Pebble's ALU; Wilkinson's polynomial
What you will be able to do
Degree
- Convert between decimal, binary and two's complement, and detect signed and unsigned overflow.
- Build a ripple-carry adder from full adders and prove it correct by induction on the bits.
- Decode an IEEE 754 number and explain why 0.1 + 0.2 is not 0.3.
Graduate
- Derive the carry operator, prove it associative and compare the prefix networks' depth, size and fan-out.
- Bound the error of naive, pairwise and Kahan summation with the model fl(x op y) = (x op y)(1 + delta).
- Separate a problem's conditioning from an algorithm's stability, using Wilkinson's polynomial.
Research
- State the known upper and lower bounds on integer multiplication and what the n log n algorithm leaves open.
- Explain the table-maker's dilemma and what a correctly rounded elementary function requires.
Industry
- Choose between integers, fixed point, decimal and floating point for money, counters and measurements.
- Explain how the FDIV table bug escaped random testing and what verification replaced it.
- Compare binary16, bfloat16 and FP8 and say why machine learning traded precision for range.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 29 min · Graduate 48 min · Research 52 min · Industry 35 min.
- 0Numbers that run outDegree2 min
- 1Bits as numbersDegree2 min
- 2Integers on a clockDegree4 min
- 3Adding, one bit at a timeDegree4 min
- 4Carries in parallelGraduate5 min
- 5The adders, racedGraduate2 min
- 6MultiplicationDegree3 min
- 7Division, and a famous bugIndustry5 min
- 8Pebble's ALUDegree3 min
- 9Fixed pointDegree2 min
- 10Floating pointDegree4 min
- 11Rounding errorDegree4 min
- 12Conditioning and stabilityGraduate3 min
- 13Beyond IEEEIndustry1 min
- 14Computing sin, exp and logGraduate3 min
- 15Frontier: arithmetic's open questionsResearch4 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Numbers that run outDegree2 min
In December 2014, YouTube announced that one music video had been watched more times than its view counter was ever designed to hold. The count had been kept in a signed thirty-two-bit integer, and the largest number that fits is two to the thirty-one, minus one: two billion, one hundred and forty-seven million and some. One more than that, and such a counter does not grow. It wraps around, to minus two billion. This animation models a signed two's-complement counter. YouTube had already upgraded to sixty-four bits before the milestone, which will last a while.
In Python or JavaScript, ask for zero point one plus zero point two. The answer is not zero point three. It is zero point three, then fifteen zeros, then a four. Python says so, JavaScript says so: these expressions use binary64 floating point. Other formats can round differently. None of them is broken.
All three stories have one cause. A machine has only finitely many bits. So its integers do not go on forever: they live on a clock, and going past the top brings you round to the bottom. And its real numbers are not a continuum. They are a sparse ruler, finely marked near zero and coarsely marked far away, and every answer is rounded to the nearest mark. This part builds the arithmetic of Pebble on top of those facts: the circuits that add, multiply and divide, as fast as gates allow, and the number formats that every calculation in the rest of the series runs on, with the ways they can bite.
1Bits as numbersDegree2 min
Two thousand and twenty-six means two thousands, no hundreds, two tens and six ones. A digit's value depends on its place, and each place is worth ten times the one to its right. Nothing about this needs ten. In base two each place is worth twice the one to its right, and each digit is a zero or a one: a bit. Two thousand and twenty-six is eleven bits: the places worth one thousand and twenty-four, five hundred and twelve, and so on, wherever there is a one. Add those up, and you get the number back. With n bits there are two to the n patterns, so they can count from zero to two to the n minus one; and a positive integer N needs about log base two of N bits. Gottfried Leibniz worked all of this out in 1679, and thought it so elegant that he saw creation in it: everything from one and nothing.
To go the other way, from a decimal number to its bits, keep halving. Two thousand and twenty-six is even, so its lowest bit is zero; half of it is one thousand and thirteen, which is odd, so the next bit is one; and so on down to zero. Reading the remainders from the bottom up gives the bits from the top down. It works because halving a binary number shifts every bit one place to the right, and the remainder is the bit that falls off the end. Every routine that prints a number, in any base, is this loop.
2Integers on a clockDegree4 min
Four bits make sixteen patterns. Lay them around a clock face, zero at the top, counting clockwise to fifteen. Adding is turning the hand: to add five, go five clicks. Thirteen plus five goes past fifteen and comes round to two. Eighteen does not fit in four bits, so the hardware keeps eighteen minus sixteen. The sixteen that went missing is the carry out of the top bit. This is arithmetic modulo two to the n, the integers on a clock, and every adder in this part computes it: it is the most honest description of what a register holds.
Now the trick that every computer uses for negative numbers. Keep the clock, and relabel patterns eight through fifteen: fifteen is one step before zero, so call it minus one; fourteen is minus two; down to eight, which becomes minus eight. Thirteen is now minus three, and turning five clicks still lands on two. Minus three plus five is two. Nothing changed but the labels: the same bits, and the same adder, serve signed and unsigned numbers. In formulas, the top bit counts as minus two to the n minus one instead of plus, and so it doubles as the sign. One, one, zero, one is minus eight plus four plus one: minus three. This is two's complement, proposed by John von Neumann in 1945, and it won because the hardware gets it for free.
How do you negate a number? Add any x to its bitwise inverse, and every bit is a one: the pattern for minus one. So minus x equals the inverse of x, plus one. Six is zero zero zero zero zero one one zero; invert it, add one, and you have minus six. One hundred works the same way. To widen a number from four bits to eight, copy its sign bit into the new places: one one zero one is minus three, and so is one one one one, one one zero one, because the new minus one twenty-eight and the extra ones add up to the old minus eight. One oddity: the most negative number has no positive partner. Negate minus one hundred and twenty-eight in eight bits, and you get minus one hundred and twenty-eight back.
The clock has an edge, and crossing it is overflow. In signed four-bit arithmetic, five plus four goes past seven and lands on minus seven. The adder cannot know whether you meant signed or unsigned, so it reports both kinds of trouble. For unsigned numbers, overflow is a carry out of the top bit. For signed numbers it is subtler: the result is wrong exactly when the carry into the top bit differs from the carry out of it, which happens when two positives give a negative or two negatives a positive. One exclusive-or gate detects it. Languages disagree about what to do. In C, signed overflow is undefined behaviour, and compilers optimize as if it never happens; Java and Go wrap around the clock; Rust panics in debug builds; Python's integers simply grow. Integer overflow is still behind a steady stream of security holes.
3Adding, one bit at a timeDegree4 min
Adding binary numbers works exactly like the method from school, with fewer facts to remember. Eleven plus six: start at the right. One plus zero is one. One plus one is two, which in binary is one zero: write zero, carry one. Zero plus one plus the carry is two again: write zero, carry one. One plus zero plus the carry: zero, carry one, and that last carry becomes a new top digit. Seventeen. Every column does the same small job: three bits come in, the two digits and the carry, and two bits go out, a sum and a carry for the next column. Build that job once in gates, copy it n times, and you can add.
Start with two bits. Their sum is a two-bit number: the low bit is one when exactly one input is one, an exclusive-or; the high bit, the carry, is one when both are, an and. That is a half adder. A column in the middle of a sum has three inputs, the two digits and the carry from the right. The sum bit is the exclusive-or of all three: it is one when an odd number of them are. The carry out is one when at least two of them are: the majority function from Part 3. In gates: one half adder adds a and b, a second adds the carry in, and an or combines the two possible carries, which can never both be one. Five gates. This is the full adder, and it is the atom of computer arithmetic.
Now copy the full adder, once per bit, and chain them. Bit zero on the right takes a carry in; each adder's carry out becomes the next one's carry in; the last carry out is the top bit of the answer, or, in a register of fixed width, unsigned overflow. This is the ripple-carry adder: n full adders, five n gates. And the same carry chain can subtract. Since minus b is not b plus one, a minus b is a plus not b plus one: put an exclusive-or on each b input to invert it, and feed a one into the carry. One circuit, two operations, signed or unsigned.
There is a catch, and it is time. Add one to zero, one, one, one, one, one, one, one. Bit zero produces a carry; bit one cannot know its sum until that carry arrives; then it produces a carry for bit two, and so on. Simulated gate by gate, with every gate taking one unit of time, the sum bits settle one after another, two gate delays apart, from the right to the left. The worst case grows in step with the width: two n plus one gate delays. For sixty-four bits that is a hundred and twenty-nine, when Part 3's clock budget allowed a processor about twenty-five per cycle. A ripple-carry adder is correct, small and far too slow. The next chapter is about breaking the chain.
4Carries in parallelGraduate5 min
To break the chain, look at what one column does with a carry, before knowing what the carry is. If both of its bits are one, it sends a carry out no matter what comes in: it generates. If exactly one bit is one, a carry that comes in goes straight out: it propagates. If both are zero, no carry leaves: it kills. These three cases depend only on the column's own two bits, so every column knows its letter after one gate delay, all at once. In symbols: g is a and b, p is a exclusive-or b, the carry out is g, or p and the carry in, and the sum bit is p exclusive-or the carry in. The whole problem of fast addition is now computing every carry from these letters quickly.
Here is the algebra. Think of a column, or any block of columns, as a function from the carry that comes in to the carry that goes out. There are only three such functions: kill sends everything to zero, propagate is the identity, and generate sends everything to one. Every block is one of them, and is described by its pair, g and p. Putting a high block after a low one is composing their functions, and the pair of the combination is g plus p g prime, and p p prime. Composition of functions is always associative, so this operator is too: combine three blocks either way and you get the same pair. That one fact is the key. It means the carries are prefix combinations, like running totals, and running totals of an associative operation can be computed by a tree instead of a chain, in logarithmic depth.
Draw the sixteen positions as columns, bit zero on the right, and draw a dot wherever two blocks are combined. The ripple adder is a chain: position one absorbs position zero, then two absorbs that, and so on, one combine per level, fifteen levels deep. Fifteen combines, the fewest possible, and the slowest.
In 1973 Peter Kogge and Harold Stone published the fastest arrangement. At the first level every position combines with its neighbour one to the right; at the second, with the position two to the right; then four, then eight. After four levels every position holds the combination of everything below it: all sixteen carries, in log two of n levels. The price is size, forty-nine combines, and wiring: the long diagonal wires are what make real Kogge-Stone adders hard to lay out.
Richard Brent and H. T. Kung found the frugal arrangement in 1982. Build a binary tree upwards, combining pairs, then pairs of pairs, until the top position holds the whole sum; then send the partial results back down the tree to fill in the positions between. Twenty-six combines, fewer than twice the ripple's, in seven levels: about two log n. The same up-and-down sweep is the parallel scan of Part 10, which sums, sorts and allocates on graphics processors.
The oldest is Jack Sklansky's, from 1960, and it is divide and conquer. Solve the low half and the high half separately, then let the top result of the low half fan out to every position in the high half, and do the same inside each half. Four levels, as fast as Kogge-Stone, with thirty-two combines. But one value must drive eight gates at once, and Part 3 showed that fan-out costs time. Every real adder is a compromise between these three.
Side by side, for sixteen positions. The ripple chain is smallest and deepest. Kogge-Stone is shallowest and biggest, with fan-out two but a forest of long wires. Brent-Kung is nearly as small as the ripple at twice Kogge-Stone's depth. Sklansky is shallow and small, but with a fan-out of nine. And there is a theorem saying you cannot have everything: Marc Snir proved in 1986 that for any prefix network, the size plus the depth is at least two n minus two. Designers of real chips use hybrids, Han-Carlson, Ladner-Fischer and others, tuned to the wires and gates of each process.
5The adders, racedGraduate2 min
Now race them. Every adder here is a netlist from this series' hardware library, checked against Python's integers on every input at eight bits and on thousands of chosen inputs up to sixty-four, then timed gate by gate. On the left, delay against width. The ripple adder climbs in a straight line; carry-skip and carry-select bend like square roots; the three prefix adders barely rise, adding a couple of gate delays each time the width doubles. On the right, the bill. The ripple adder is cheapest, Kogge-Stone grows like n log n and costs more than three times as much at sixty-four bits, and carry-select pays for its duplicated work. Brent-Kung costs half again as much as the ripple, and is five times faster.
At sixty-four bits, the numbers side by side. The ripple adder: three hundred and twenty gates, a hundred and twenty-nine delays. Kogge-Stone: about a thousand gates, fifteen delays, almost nine times faster for three and a half times the gates. That trade, spending area to buy time, is the theme of every chapter on hardware in this series. Real processors make it every time: their adders are prefix trees, tuned to the length of their wires, and they add sixty-four bits in a fraction of a clock cycle. Pebble's arithmetic unit will use Kogge-Stone.
6MultiplicationDegree3 min
Multiplication in binary is the schoolbook method with the times table thrown away. To multiply eleven by thirteen, go through the bits of thirteen from the right. Each bit is a zero or a one, so each row is either nothing or eleven itself, shifted one more place left. Add the rows and you have a hundred and forty-three. In gates, each digit of each row is a bit of a anded with a bit of b, so the rows cost n squared and gates all at once, in one gate delay. Everything else is adding n numbers together, and the question, again, is how fast.
The better idea is to stop adding, in the usual sense. Take three numbers. Put a full adder on every column, all side by side, each adding the three bits in its own column. Each full adder makes a sum bit, which stays in its column, and a carry bit, which belongs one column to the left. Collect the sums into one number and the carries into another. The three numbers have become two with the same total, and it took one full-adder delay, no matter how wide the numbers are, because no carry travelled anywhere. This is carry-save addition, and a full adder used this way is called a three-to-two compressor.
In 1964 Chris Wallace put this to work on all the partial products at once. Draw every partial-product bit of an eight-by-eight multiplication as a dot in its column: sixty-four dots, piled eight high in the middle. In every column, group the dots in threes and send each group through a full adder: one dot stays, one moves left. Every column shrinks to about two thirds of its height, all at the same time. Eight becomes six, then four, then three, then two. Two rows are left, and one fast prefix adder from chapter four finishes the job. Because each stage cuts the height by a constant factor, the number of stages grows like the logarithm of n. At sixteen bits the tree needs six stages and twenty-eight gate delays, where the array needed eighty-eight. Luigi Dadda's refinement of 1965 compresses only as much as each stage requires, and saves gates for the same depth.
7Division, and a famous bugIndustry5 min
Division is the hard one, because each digit depends on the remainder left by the one before. The schoolbook method, in binary: bring down the next bit of two hundred, and try subtracting thirteen. If it fits, the quotient bit is one and the difference becomes the remainder. If it does not, the bit is zero and the old remainder is restored. Eight steps give fifteen, remainder five. That is one quotient bit per subtraction, and every subtraction waits for the last, so a sixty-four-bit division takes sixty-four of them. Skipping the restore, and adding the divisor back on the next step instead, saves a little; it is called non-restoring division. To go faster, you have to produce more than one bit per step, and that needs a cleverer idea.
In 1958 Dura Sweeney at IBM, James Robertson at Illinois and Keith Tocher in London found that idea, independently, and division with it carries their initials: SRT. Work in base four, so each step makes two bits of quotient, and allow negative digits: each quotient digit is one of minus two, minus one, zero, one or two. The remainder is kept within two thirds of the divisor. Here is why that helps. For each digit, draw the range of remainders it can handle without the next remainder leaving the band. The ranges overlap. Near a boundary, two digits are both right, and either choice is corrected automatically by the digits that follow. So the hardware never needs the exact remainder to choose. A handful of its leading bits, and a few leading bits of the divisor, are enough to look the digit up in a small table, while the full subtraction happens in carry-save form, with no carries to wait for.
Here is that table, built for this video: the same shape as a real radix-four divider's. Across, the divisor, from one to two; up, an estimate of four times the remainder. Each little cell is coloured by the quotient digit it holds, and each digit was checked against every point of its cell: whatever the true values inside, that digit keeps the next remainder in range. The staircases are the overlaps of the last picture, seen in two dimensions. Run four hundred thousand random divisions through it, and a striking thing appears: hundreds of cells, near the top and bottom edges, are never visited at all. The divisions come out right to the last bit. And the never-visited cells are exactly where trouble hides.
In 1994 Thomas Nicely, a mathematician in Virginia, was adding up the reciprocals of twin primes on a new Intel Pentium, and the sums came out wrong. The cause was the table. Intel's divider used radix-four SRT with a table of one thousand and sixty-six entries, and five of them, on the upper edge, held zero where they should have held two: they had been assumed unreachable. The most famous example: four million, one hundred and ninety-five thousand, eight hundred and thirty-five divided by three million, one hundred and forty-five thousand, seven hundred and twenty-seven is one point three three three eight two; the Pentium said one point three three three seven three, wrong in the fourth decimal place. We can do the same to our table. Empty the highest cell that random divisions ever visit, in five columns, and run two million divisions. Almost one in a hundred now comes out wrong, some badly, because a wrong digit throws the remainder out of the band and no later digit can bring it back. Intel's cells were reached about once in nine billion random divisions, which is why its testing missed them. Intel first said most users would never notice, then replaced the chips, for four hundred and seventy-five million dollars. Since then, chip arithmetic has been proved correct by machine, as Part 54 will show.
8Pebble's ALUDegree3 min
Pebble's processor will need one unit that does all of its arithmetic and logic, the ALU. Here are the operations its instruction set asks for. An adder, which also subtracts by inverting b and setting the carry in. A logic unit, which is just one and, one or and one exclusive-or per bit. A barrel shifter, from Part 3, extended to shift right as well, filling with zeros or with copies of the sign bit. And comparisons, which reuse the adder's flags with a little extra logic, as we will see. All of them compute at once, on every instruction, and a four-bit operation code selects which answer leaves, through a multiplexer on every output bit. Two flags come out too: whether the result is zero, which branches will test, and whether a signed add overflowed. Ten operations in all, exactly the ones Pebble's emulator implements.
How does an adder compare? For unsigned numbers, a is less than b exactly when a minus b has to borrow, and in two's complement subtraction a borrow shows up as a carry out of zero. For signed numbers, look at the sign of a minus b, but correct it with the overflow bit. Minus three minus two is minus five: the sign is one, no overflow, so minus three is less. Minus eight minus one should be minus nine, which does not fit in four bits; it wraps round to plus seven, with a sign of zero, but the overflow flag is set, and flipping the sign gives the right answer. Getting this wrong is a classic bug in hand-written assembly: comparing by the sign of a difference works until the numbers get large.
This ALU exists, as a netlist in the series' library. The eight-bit version was checked on every one of its six hundred and fifty-five thousand cases: every pair of operands, for all ten operations. The thirty-two-bit version was checked on twenty thousand inputs, random ones and worst-case carries and borrows, against exactly what Pebble's emulator computes. With a ripple adder inside, the thirty-two-bit ALU has about sixteen hundred gates and its largest observed delay in these tests is seventy-eight. With Kogge-Stone, about three hundred gates more, the observed delay is twenty-nine. The fast adder costs a fifth more gates and makes the whole unit almost three times faster, because addition was the slowest thing in it. Rewritten in NAND gates alone, it is about four and a half thousand of them. In Part 6 this circuit becomes the heart of Pebble.
9Fixed pointDegree2 min
The integer hardware we have built can hold fractions, with one agreement. Decide that the binary point sits in a fixed place, say four bits from the right. The places to its left are worth minus eight, four, two and one in signed two's complement; to its right, a half, a quarter, an eighth and a sixteenth. Then these eight bits mean five point six two five, which is the integer ninety divided by sixteen. This is signed Q four point four, counting the sign among the four integer bits. Conventions differ, so state yours. Addition and subtraction use the same integer circuits, with a chosen overflow policy. Multiplication needs a wide integer product, rescaled by sixteen, with explicit rounding and overflow rules. The scale is an agreement; it does not remove the need to manage precision.
What fixed point cannot do is range. Science deals with numbers from the mass of an electron, about ten to the minus thirty kilograms, to the mass of the Sun, about ten to the thirty. A thirty-two-bit fixed-point number with sixteen bits on each side of the point covers nine decades, from about one sixty-thousandth to about thirty thousand, with the same absolute spacing everywhere: superb near thirty thousand and useless near zero. Classic Doom did its geometry in exactly this format, and signal processors and embedded chips still live in it. To cover all of science you would need two hundred bits. Instead, let the point float: store the digits and, separately, where the point goes. A thirty-two-bit floating-point number has a normal range spanning seventy-six decades with about seven significant digits. Subnormals extend it towards zero with less precision. That is the next chapter.
10Floating pointDegree4 min
In 1985 the IEEE published a standard, led by William Kahan of Berkeley, that ended a decade of every company doing floating point its own way. A number is stored like scientific notation, in binary: a sign, an exponent and a fraction. For normal numbers, the value is plus or minus one point f, times two to the power e minus a bias. In thirty-two bits: one bit of sign, eight of exponent, twenty-three of fraction. Here is zero point one. Its exponent field says two to the minus four; its fraction says one point six, nearly. The number actually stored is zero point one, zero zero zero, zero zero zero, one four nine and more: the closest float to a tenth, but not a tenth. Two tricks make the format efficient. The leading one of a normalized number is always one, so it is not stored, buying a free bit. And the exponent is stored with a bias, so that comparing nonnegative finite floats as unsigned bit patterns gives the right order; NaNs are excluded.
To see the shape of this ruler, shrink the format until every value fits on the screen. Six bits: a sign, three bits of exponent and two of fraction. Here are all of its positive finite values. Between one and two there are four of them, a quarter apart. Between two and four, four more, half apart; between four and eight, four more, one apart. Every power of two begins a new band, with the same number of marks and twice the spacing. The ruler is uniform in relative terms, logarithmic in absolute ones. Near zero, a special rule takes over. When the exponent field is all zeros, the hidden leading one becomes a zero, and the values continue evenly down to zero. These are the subnormal numbers.
The gap between a float and the next one up is called an ulp, a unit in the last place. In thirty-two-bit floats, the ulp of one is two to the minus twenty-three, about one ten-millionth; between two and four it is twice that, and so on. Divide the ulp by the number itself, and you get a sawtooth that never leaves a factor of two: normal floats, large or small, have approximately the same relative precision. Two to the minus twenty-three is the format's machine epsilon. Half of it, called u, bounds the relative error of rounding any real number to the nearest float, provided we stay in the normal range and avoid overflow. For sixty-four-bit doubles, epsilon is about two times ten to the minus sixteen: sixteen decimal digits. One consequence surprises people. Above two to the twenty-four, sixteen million, a thirty-two-bit float's ulp is two, and the odd integers are simply gone: sixteen million, seven hundred and seventy-seven thousand, two hundred and seventeen rounds to the even number below it.
The heart of the standard is one sentence. The result of adding, subtracting, multiplying, dividing or taking a square root must be the exact mathematical answer, rounded once to the nearest float. The hardware may use any method it likes inside, extra bits, the SRT divider, Newton's iteration, but what comes out must be as if it had computed exactly. On a ruler with two fraction bits, the true result is rounded to the nearest mark. When it lands exactly halfway, it goes to the neighbour whose last bit is zero, so that ties do not drift upwards on average. This rule is what makes error analysis possible: every operation is exact, up to one rounding, with a relative error no bigger than u. The next chapter is about what happens when many such small errors meet.
11Rounding errorDegree4 min
Away from overflow and underflow, the rounding rule gives a simple relative-error model. The computed result is the exact result times one plus delta, where delta is at most u in size: about six parts in a hundred million for single precision, about one in ten million billion for double. So every single operation is very accurate, relative to its own answer. Trouble only comes from what later operations do with those errors, and it comes in two main forms. Subtracting two nearly equal numbers turns small relative errors into huge ones. And adding up very many numbers lets errors pile up. James Wilkinson built the whole of numerical analysis on this model in the 1960s.
Here is cancellation, in a function that should be harmless. One minus cos x, over x squared, tends to one half as x goes to zero. Compute it as written, in double precision, for smaller and smaller x. Down to a ten-thousandth it is fine. Then it wobbles, and at ten to the minus eight it collapses to zero. The reason: cos x is very close to one, so one minus cos x subtracts two numbers whose leading digits agree. Those digits cancel, and what is left is mostly the rounding error in cos x, now magnified by one over x squared. At ten to the minus eight, cos x rounds to exactly one. The cure is algebra, not more bits: rewrite one minus cos x as two sine squared of x over two, which subtracts nothing, and the answer stays accurate for small nonzero x.
The second danger is accumulation. Add up a million random numbers in single precision, one at a time. Once the running sum is large, each new small number loses its low bits when it is added, and the losses pile up: the relative error grows with n, and by a million terms it is around ten to the minus five, a hundred times u. Adding in pairs, then pairs of pairs, a tree like chapter four's, keeps the error growing only like log n; numpy does this by default. William Kahan's compensated summation, from 1965, does better with four lines. It keeps a second variable, c, approximating the low bits that the last addition threw away, and feeds them back into the next one. Its error bound does not grow with n at all, to first order, and the curve is flat. Python's math dot fsum tracks partial sums for very high accuracy; some platforms can still double-round the last bit.
In the Gulf War, a Patriot missile battery in Dhahran had been running for about a hundred hours. Its clock counted tenths of a second as an integer, and to get time in seconds the software multiplied by one tenth, kept in a twenty-four-bit fixed-point register. One tenth has no finite binary expansion, so the register held it chopped: too small by about ten to the minus seven seconds per tick. After a hundred hours, three point six million ticks, the clock was a third of a second slow. A Scud missile covers more than half a kilometre in a third of a second, and the radar looked in the wrong place. On the twenty-fifth of February 1991 the battery failed to intercept a Scud, and twenty-eight soldiers were killed. The corrected software, already on its way, arrived the next day.
12Conditioning and stabilityGraduate3 min
When a computed answer is wrong, there are two different suspects. The first is the problem itself. Its condition number measures how much a small relative change in the input can change the exact answer. Subtracting two nearly equal numbers is badly conditioned: a tiny change in either changes the difference enormously. The second is the algorithm. A backward-stable algorithm returns the exact answer to a slightly perturbed question, perturbed by about u. Put together, the error of a stable algorithm is about the condition number times u. For chapter eleven's function, the relative condition number is the absolute value of x cotangent of x over two, minus two. Near zero it is about x squared over six, tending to zero. The problem is well conditioned there; the naive formula is unstable. Rewriting it restores accuracy. But if the problem itself is ill conditioned, no algorithm can recover information already lost in the input. James Wilkinson found that out, painfully, in 1959.
Wilkinson was testing a root-finding program on the Pilot ACE computer in London, and chose an easy polynomial: the one whose roots are one, two, three, up to twenty. Multiplied out, its coefficients are huge integers, from minus two hundred and ten down to twenty factorial. Here are its roots, the integers on the real line. Now change one coefficient, the minus two hundred and ten in front of x to the nineteen, by two to the minus twenty-three, about one part in two billion of it, and watch the roots, computed here with sixty-digit arithmetic so that no rounding interferes. The small roots barely move. The large ones collide in pairs and leave the real line: ten of them become complex, with imaginary parts as large as two point eight. This is not rounding error. It is the exact answer to the slightly different question. Wilkinson later called it the most traumatic experience of his career as a numerical analyst.
Why are the large roots so fragile? Differentiate the equation p of r equals zero with respect to that coefficient, and the sensitivity of root k comes out as k to the nineteen, over the product of its distances to all the other roots. For the small roots that is modest. For roots in the middle teens, k to the nineteen is astronomical, and the product below it is not: root sixteen has a sensitivity of about two billion. Two billion times a change of a ten-millionth is a change of hundreds, far beyond the linear estimate's range, which is why the roots do not just shift but leave the line. The problem of finding roots from coefficients is ill conditioned, and nothing about the algorithm can fix that.
13Beyond IEEEIndustry1 min
Machine learning answered that question in an unusual way. Google Brain's bfloat16 shares the high-bit layout of a single-precision float: eight exponent bits and seven fraction bits. Conversion normally rounds, rather than just discarding the low bits. IEEE's half precision made the opposite choice, five exponent bits and ten of fraction. For many neural networks, bfloat16 is useful. Gradients span many decades, and its wide exponent range reduces underflow compared with binary16. Many models tolerate low precision, but not every quantity does; accumulation and training recipes still matter. Fewer bits also means more numbers per transfer from memory, which is usually the real bottleneck, and a significand multiplier's area grows roughly with the square of the fraction width. In 2022 the industry agreed on two eight-bit formats, one with more precision for weights and activations and one with more range for gradients. Part 17 of AI, Built trains a model in these formats and measures what they cost.
14Computing sin, exp and logGraduate3 min
A chip can only add, multiply and divide, so every other function must be built from those. The first step is always to make the argument small. For the exponential, write x as k times log two plus a small remainder r; then e to the x is two to the k times e to the r, and multiplying by two to the k adjusts the exponent for normal, in-range results. Subnormal rounding and overflow need special handling. For the sine, subtract a multiple of pi over two, and the problem becomes a sine or cosine of something less than pi over four. It sounds easy, but for an argument like ten to the twenty-two, the subtraction needs pi to over a hundred bits, or the remainder is pure noise; Mary Payne and Robert Hanek showed how to do it in 1983. For the logarithm, the float's own exponent field already did most of the work.
On the small interval, a polynomial does the rest, and the obvious choice, the Taylor series, is the wrong one. Here is the error of e to the x minus its degree-four Taylor polynomial, on the reduced interval. It is perfect at zero and worst at the ends, about four times ten to the minus five. The best polynomial of the same degree, the one that minimizes the largest error, spreads its error evenly. Its error curve touches its maximum six times, alternating in sign: Chebyshev's equioscillation theorem says that is exactly what the best polynomial looks like. With the same five coefficients, the error is seventeen times smaller. Evgeny Remez's exchange algorithm, from 1934, finds it. Libraries often use near-minimax polynomials, with coefficient rounding constraints, tables or rational approximations. Our degree-four polynomial can use Horner's rule: four multiplications and four additions.
There is also a way to compute sines with no multiplier at all, born in a navigation computer. Start with a vector along the x axis, and the angle you want in a register z. At step i, rotate the vector by plus or minus the angle whose tangent is two to the minus i, whichever moves it towards the target, and subtract that angle from z. A rotation by such an angle needs only multiplications by two to the minus i, which are shifts, plus additions. The rotations stretch the vector by the same factor every time, whichever way they turn, so one constant, K, about zero point six one, fixes it at the end. Each step adds about one bit of accuracy. Jack Volder invented this in 1959 for the B-58 bomber's navigation computer, and it is called CORDIC.
15Frontier: arithmetic's open questionsResearch4 min
Chapter six multiplied numbers the way school does, in time proportional to the square of their length. How fast can it really be done? Here are two multipliers already inside Python, timed on this machine. Python's integers switch to Karatsuba's method, which Part 19 derives, and their time grows like the length to the power of about 1.4. Python's decimal module, for very long numbers, multiplies with a number-theoretic transform: a fast Fourier transform done in modular arithmetic, so that no rounding happens at all. Its time grows almost linearly, and at a million digits it is about 6 times faster.
The theory went further than any library. Anatoly Karatsuba broke the square in 1960, Toom and Cook pushed the exponent towards one, and in 1971 Arnold Schönhage and Volker Strassen used the fast Fourier transform to reach n log n times log log n, and conjectured that n log n was the truth. Martin Fürer improved the last factor in 2007, and in 2019 David Harvey and Joris van der Hoeven reached n log n itself, with a Fourier transform in one thousand seven hundred and twenty-nine dimensions. An illustrative asymptotic crossover estimate is two to the seventeen-twenty-nine to the twelfth bits, far beyond practical sizes. That is not a measured or exact threshold. Is n log n optimal? We have a linear unconditional lower bound. A 2019 result gives n log n circuit size for constant-degree Boolean circuits, conditional on a conjecture about network coding. It is not an unconditional runtime bound.
The second question is about chapter fourteen's functions. The IEEE standard requires addition, subtraction, multiplication, division and square root to be correctly rounded: the exact answer, rounded once. For the exponential, the logarithm and the sines it only recommends it. So we tested the single-precision exponential of NumPy, on this machine, on ten million random inputs, against a float64 exponential rounded to float32. We rechecked two hundred disagreements at two hundred bits; that validates those cases, not every reference value. About 39 percent disagree with the reference, by one unit in the last place or, rarely, 2. Accuracy and speed depend on the library, CPU and vector path. These measurements show why a last-bit guarantee needs more than random testing.
Why is correct rounding hard? Rounding means deciding which of two neighbouring floats the true value is nearer to, which side of halfway it lies. When it lies extremely close to halfway, you have to compute many more digits than the answer itself has before you know. This is the table-maker's dilemma, as old as printed tables of logarithms. How many more? Rigorous error bounds and worst-case searches can answer that. Structured methods can exclude whole ranges rather than evaluate every input. Work by Vincent Lefèvre, Jean-Michel Muller and others found binary64 cases requiring more than twice its fifty-three bits to resolve. CORE-MATH already provides single-precision and many double-precision routines, with proofs for several binary64 functions. As of November 2026, the project reports seven binary64 functions integrated into GNU libc two point forty-three. Complete certified coverage, speed and wider adoption remain active work. This part's research problem explores a bounded search for hard single-precision inputs, and asks what extra evidence would make the search a certificate.
Recap, problems, and where this comes backAll tracks2 min
What we built in this part. Integers on a clock, with two's complement letting one adder serve signed and unsigned numbers. The ripple-carry adder, and the associative carry operator that turns addition into a parallel prefix, logarithmic in depth. Multipliers as trees of carry-save adders, and division by SRT, with the table that cost Intel half a billion dollars. Pebble's ALU, built and verified. And floating point: a ruler with roughly constant relative precision in the normal range, correctly rounded operations, and the difference between an unstable formula and an ill-conditioned problem.
Where this comes back. Part 6 wires this ALU into Pebble, and Part 7 adds the multiplier and the divider to its pipeline. The parallel prefix returns in Part 10 as the scan, a basic tool of parallel programming. Overflow and integer types come back in the compiler of Part 13 and in the security of Part 55. Big integers and fast multiplication meet in Part 19 and drive public-key cryptography in Part 30. Rounding and conditioning return in optimization and in Part 52's real numbers, and machine-checked arithmetic in Part 54.
Seven problems, with full solutions in the part's notes. Pause on any of them. The sixth is a build problem: it asks you to use this series' arithmetic library yourself. The last, marked with a star, is a research problem: a bounded search for hard single-precision exponential inputs. Separate the fast screen from high-precision candidate checks, and ask what would certify its coverage.
Next time: memory and time. Every circuit in this part forgets its answer the moment its inputs change. Feed a gate's output back into its own input, and it can remember. Part 5 builds latches and flip-flops, the clock that keeps them in step, the strange physics of metastability, finite state machines, and the registers and memories Pebble will run on.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 6 wires this ALU into Pebble, and Part 7 adds the multiplier and the divider to its pipeline. The parallel prefix returns in Part 10 as the scan. Overflow and integer types come back in the compiler of Part 13 and the security of Part 55; big integers and fast multiplication meet in Part 19 and drive the public-key cryptography of Part 30; rounding and conditioning return in Part 52, machine-checked arithmetic in Part 54.
Key results
The part's results in one place, for revision.
Try it
Lab 4 · Carries in a chain and in a tree; rounding error in a sum
Build ripple-carry and Kogge-Stone adders of 4 to 64 bits as netlists, check them against integer addition on random and worst-case inputs, and time them in unit gate delays. Then add 100,000 float32 numbers naively, pairwise and with Kahan's compensation, and compare the errors.
python -m videos.cs.labs 4
needs numpy, scipy, matplotlib · download lab04.py ·
source on GitHub64-bit ripple adder 320 gates, settles in 129 gate delays
64-bit kogge-stone adder 1,094 gates, settles in 15 gate delays
ripple delay at 4 ... 64 bits [9, 17, 33, 65, 129] (2n + 1: [9, 17, 33, 65, 129])
Kogge-Stone delay [7, 9, 11, 13, 15] (2 log2 n + 3: [7, 9, 11, 13, 15])
sum of 100,000 float32: naive relative error 3.6e-06 (bound n u = 6.0e-03)
pairwise relative error 4.0e-08 (bound log2(n) u = 9.9e-07)
Kahan relative error 3.8e-08 (about 2u = 1.2e-07)
worst from 10,000 numbers on naive 4.6e-06, Kahan 5.9e-08
The same sum takes 129 gate delays in a chain and 15 in a prefix tree, at three times the gates; and the same numbers added in a different order lose about two decimal digits or none.
The code (106 lines; it asserts its own result)
"""Lab 4: race a ripple-carry adder against a Kogge-Stone adder gate by gate, then sum floats three ways."""
import numpy as np
from videos.coursekit import labs
from explainer.cs.pebble import blocks, hdl
TITLE = "Carries in a chain and in a tree; rounding error in a sum"
GOAL = ("Build ripple-carry and Kogge-Stone adders of 4 to 64 bits as netlists, check them against integer "
"addition on random and worst-case inputs, and time them in unit gate delays. Then add 100,000 float32 "
"numbers naively, pairwise and with Kahan's compensation, and compare the errors.")
TASKS = [
"Add 'brent-kung' and 'sklansky' to KINDS. Which has the fewest gates, and what does it pay in delay or fan-out?",
"Time blocks.carry_skip_adder(32) with settle() and compare with its depth(): why is the deepest path never exercised?",
"Sort the numbers by decreasing size before the naive sum, then by increasing size. Which order loses less?",
]
KINDS = ("ripple", "kogge-stone")
def adder(n, kind):
return blocks.ripple_adder(n) if kind == "ripple" else blocks.prefix_adder(n, kind)
def kahan(x):
"""Kahan's compensated sum in float32; returns the running sums."""
s, c, out = np.float32(0), np.float32(0), np.empty(len(x), np.float32)
for i, v in enumerate(x):
y = v - c
t = s + y
c = (t - s) - y # what the addition just lost, recovered exactly
s = t
out[i] = s
return out
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the adders: correct on every test vector, and timed
widths = [4, 8, 16, 32, 64]
delay = {k: [] for k in KINDS}
gates = {k: [] for k in KINDS}
for n in widths:
a = rng.integers(0, 2 ** n, 2000, dtype=np.uint64, endpoint=False)
b = rng.integers(0, 2 ** n, 2000, dtype=np.uint64, endpoint=False)
cin = rng.integers(0, 2, 2000, dtype=np.uint64)
a[:2], b[:2], cin[:2] = (2 ** n - 1, 0), (0, 2 ** n - 1), (1, 1) # a carry that travels the whole word
want = [int(x) + int(y) + int(z) for x, y, z in zip(a, b, cin)]
for kind in KINDS:
c = adder(n, kind)
out = hdl.simulate(c, {"a": a, "b": b, "cin": cin})
got = [int(s) + (int(co) << n) for s, co in zip(out["s"], out["cout"])]
assert got == want, f"{n}-bit {kind} adder disagrees with integer addition"
t = c.settle({"a": a.view(np.int64), "b": b.view(np.int64), "cin": cin.view(np.int64)})
delay[kind].append(int(t.max()))
gates[kind].append(c.size())
for kind in KINDS:
lab.row(f"64-bit {kind} adder", f"{gates[kind][-1]:,} gates, settles in {delay[kind][-1]} gate delays")
lab.row("ripple delay at 4 ... 64 bits", f"{delay['ripple']} (2n + 1: {[2 * n + 1 for n in widths]})")
lab.row("Kogge-Stone delay", f"{delay['kogge-stone']} (2 log2 n + 3: {[2 * int(np.log2(n)) + 3 for n in widths]})")
assert delay["ripple"] == [2 * n + 1 for n in widths], "the carry ripples through two gates per bit"
assert delay["kogge-stone"] == [2 * int(np.log2(n)) + 3 for n in widths], "one prefix level per doubling"
assert (gates["ripple"][-1], gates["kogge-stone"][-1]) == (320, 1094), "the film's gate counts at 64 bits"
# 2. summing float32 numbers: naive, pairwise, Kahan
x = rng.uniform(0, 1, 100_000).astype(np.float32)
exact = np.cumsum(x.astype(np.float64))
naive = np.cumsum(x) # float32, one after another
comp = kahan(x)
marks = np.unique(np.geomspace(100, len(x), 25).astype(int)) - 1
pair = np.array([np.sum(x[:k + 1]) for k in marks]) # numpy's sum is pairwise
def err(s, ref):
return np.abs(s.astype(np.float64) - ref) / ref
e_naive, e_pair, e_kahan = err(naive, exact)[-1], err(pair, exact[marks])[-1], err(comp, exact)[-1]
u = 2.0 ** -24
lab.row("sum of 100,000 float32: naive", f"relative error {e_naive:.1e} (bound n u = {len(x) * u:.1e})")
lab.row("pairwise", f"relative error {e_pair:.1e} (bound log2(n) u = {np.log2(len(x)) * u:.1e})")
lab.row("Kahan", f"relative error {e_kahan:.1e} (about 2u = {2 * u:.1e})")
assert e_naive < len(x) * u and e_pair < np.log2(len(x)) * u and e_kahan <= 2 * u
worst_naive, worst_kahan = err(naive, exact)[10_000:].max(), err(comp, exact)[10_000:].max()
lab.row("worst from 10,000 numbers on", f"naive {worst_naive:.1e}, Kahan {worst_kahan:.1e}")
assert worst_kahan <= 2 * u and worst_naive > 5 * worst_kahan, "compensation recovers what the naive sum loses"
lab.note = ("The same sum takes 129 gate delays in a chain and 15 in a prefix tree, at three times the gates; "
"and the same numbers added in a different order lose about two decimal digits or none.")
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].plot(widths, delay["ripple"], "o-", color=labs.RED, label="ripple carry: 2n + 1")
ax[0].plot(widths, delay["kogge-stone"], "o-", color=labs.GREEN, label="Kogge-Stone: 2 log2 n + 3")
ax[0].set_xscale("log", base=2)
ax[0].set_xticks(widths, [str(n) for n in widths])
ax[0].set(title="Measured delay of two adders", xlabel="bits n", ylabel="gate delays until the sum settles")
ax[0].legend()
ks = marks + 1
floor = u / 8 # an error of exactly zero is drawn at the bottom of the log axis
ax[1].loglog(ks, np.maximum(err(naive, exact)[marks], floor), "o-", ms=3, color=labs.RED, label="naive, in order")
ax[1].loglog(ks, np.maximum(err(pair, exact[marks]), floor), "o-", ms=3, color=labs.GOLD, label="pairwise")
ax[1].loglog(ks, np.maximum(err(comp, exact)[marks], floor), "o-", ms=3, color=labs.GREEN, label="Kahan")
ax[1].axhline(u, color=labs.MUTED, ls="--", lw=1)
ax[1].text(ks[-1], u * 1.15, "u = 2^-24", color=labs.MUTED, fontsize=9, ha="right", va="bottom")
ax[1].set(title="Relative error of a float32 sum", xlabel="numbers added", ylabel="relative error")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Add 'brent-kung' and 'sklansky' to KINDS. Which has the fewest gates, and what does it pay in delay or fan-out?
- Time blocks.carry_skip_adder(32) with settle() and compare with its depth(): why is the deepest path never exercised?
- Sort the numbers by decreasing size before the naive sum, then by increasing size. Which order loses less?
Problems, with solutions
Try each problem before opening its solution.
-
Two's complement. Write −37 in 8 bits, and show that x ↦ x̄ + 1 fixes only 0 and −128.
Solution
37 = 00100101; inverted, 11011010; plus one, 11011011. A fixed point satisfies x = −x mod 2⁸, so 2x ≡ 0 (mod 256), x ≡ 0 (mod 128): x = 0 or x = 128, whose signed reading is −128. So −128 has no positive partner.
-
Signed overflow. Prove that a signed n-bit addition overflows exactly when the carry into the top bit differs from the carry out of it.
Solution
Let the top bits be a, b, the carry into the top position c, the carry out c′, and the top sum bit s = a ⊕ b ⊕ c. Overflow means both operands have the same sign but the result has the other: a = b ≠ s. If a = b = 0, then c′ = 0 and s = c, so overflow ⇔ c = 1 ⇔ c ≠ c′. If a = b = 1, then c′ = 1 and s = c, so overflow ⇔ c = 0 ⇔ c ≠ c′. If a ≠ b, overflow is impossible, and c′ = c (the column propagates). So overflow ⇔ c ≠ c′, which one XOR gate detects.
-
Kogge–Stone's size. Show that a Kogge–Stone network on n = 2ᵏ positions has nk − n + 1 combines.
Solution
At level l (reach d = 2ˡ) every position i ≥ d combines, n − 2ˡ of them. Summing over l = 0 … k − 1: nk − (2ᵏ − 1) = nk − n + 1. For n = 16: 64 − 16 + 1 = 49, as drawn in chapter 4 (and depth k = log₂ n).
-
Carry-save. Show that, bit by bit, x + y + z = (x ⊕ y ⊕ z) + 2·maj(x, y, z).
Solution
In each column, the three bits xᵢ, yᵢ, zᵢ add up to a number from 0 to 3, which is sᵢ + 2cᵢ with sᵢ the parity (XOR) and cᵢ the majority — the full adder's truth table. Multiply column i by 2ⁱ and sum over i: the left side is x + y + z, the right side is the word of parities plus twice the word of majorities. No carry moves between columns, so the step takes one full-adder delay for any n.
-
Floats. How many float32 values lie in [1, 2)? In Python binary64, why is 0.5 + 0.25 = 0.75 exact, but 0.1 + 0.2 ≠ 0.3?
Solution
In [1, 2) the exponent is fixed and the 23 fraction bits are free: 2²³ = 8,388,608 values (the same number in every binade [2ᵉ, 2ᵉ⁺¹) of normal numbers). 0.5, 0.25 and 0.75 are dyadic (denominators powers of two), exactly representable, and so is their exact sum, so correct rounding returns it unchanged. 0.1, 0.2 and 0.3 have infinite binary expansions; each is stored rounded, and the rounded 0.1 plus the rounded 0.2 is a different double from the rounded 0.3 (0.30000000000000004 against 0.29999999999999998…). This inequality is format-dependent: the corresponding float32 additions compare equal.
-
Build: a carry-select adder. With
explainer/cs/pebble/blocks.py, build an 8-bit carry-select adder with blocks of 2, 3 and 3 bits; verify it on all inputs; compare it with ripple and Kogge–Stone.Solution
carry_select_adder(8, [2, 3, 3]), simulated on all 2¹⁷ inputs withhdl.simulate, matches a + b + c everywhere. Measured: 94 gates, settling in 12 gate delays, against the ripple adder's 40 gates and 17 delays and Kogge–Stone's 70 gates and 9 delays (the default block sizes 1, 2, 3, 2 give 105 gates and also 12). -
★ Research: hard float32 exponential inputs. Screen float32 inputs in [−87.33, 88.72] for eˣ close to a rounding midpoint. Recheck the candidates at high precision. What would certify that none was missed?
Experiment, and its limits.
compute_hardroundscreens 2,237,667,740 bit patterns in this interval using NumPy float64exp(endpoints rounded to float32), then re-measures 200 candidates at 300 bits with mpmath. The count includes both signed zeros. It does not cover the entire float32 domain, including inputs whose exponentials are subnormal. No rigorous error bound for the float64 screen is established here, so its shortlist is an experiment, not a proof of the global hardest case.The closest shortlisted candidate is x = −14.56709003448486328125, with eˣ only 2.36 × 10⁻⁹ float32 ulp from a midpoint. The metric
24 − log₂(distance)is about 52.7 bits, a useful indication of the accuracy budget rather than an exact minimum precision theorem. The next candidates are −0.0073526 (51.7) and 1.5199 × 10⁻⁵ (51.6). At the first candidate the midpoint is about 1.265 binary64 ulps away; correctly rounding eˣ to binary64 and then float32 gives the correct float32 result. Thus this candidate does not establish that binary64 precision is insufficient. A particular fast approximation still needs a certified total error bound; an interval enclosing a midpoint must trigger refinement or a fallback.To turn the experiment into a certificate, bound the screening error and candidate-selection margin, cover excluded domains and special cases, and validate high-precision rounding with error enclosures. Structured searches and lattice methods can prune enormous ranges; evaluating every input individually is not the only method. CORE-MATH already supplies many correctly rounded binary64 routines. Extending certified coverage and improving performance and adoption remain active work.
Notes and sources
Glossary
补码 two's complement · 溢出 overflow · 符号扩展 sign extension · 半加器 / 全加器 half / full adder · 行波进位加法器 ripple-carry adder · 生成 / 传递 / 消除 generate / propagate / kill · 超前进位 carry lookahead · 并行前缀 parallel prefix · 进位选择 / 进位跳跃 carry-select / carry-skip · 伪路径 false path · 进位保留 carry-save · 华莱士树 Wallace tree · 布斯编码 Booth recoding · SRT 除法 SRT division · 牛顿–拉弗森迭代 Newton–Raphson iteration · 算术逻辑单元 ALU · 定点数 fixed point · 浮点数 floating point · 规格化数 / 次正规数 normal / subnormal number · 末位单位 ulp · 机器精度 machine epsilon · 正确舍入 correctly rounded · 灾难性抵消 catastrophic cancellation · 补偿求和 compensated summation · 条件数 condition number · 向后稳定 backward stable · 区间算术 interval arithmetic · 最佳一致逼近 minimax approximation · CORDIC
Sources
Books: Harris & Harris, Digital Design and Computer Architecture, ch. 1 and 5; Parhami, Computer Arithmetic; Koren, Computer Arithmetic Algorithms; Higham, Accuracy and Stability of Numerical Algorithms, ch. 1–4; Muller et al., Handbook of Floating-Point Arithmetic; Overton, Numerical Computing with IEEE Floating Point Arithmetic; Knuth, TAOCP vol. 2, §4.1–4.3.
Papers and reports: Booth (1951); Robertson (1958); Tocher (1958); Sklansky, "Conditional-sum addition logic" (1960); MacSorley (1961); Bedrij, carry-select (1962); Wallace (1964); Dadda (1965); Kahan, compensated summation (1965); Kogge & Stone (1973); Brent & Kung (1982); Payne & Hanek (1983); Wilkinson, Rounding Errors in Algebraic Processes (1963) and "The perfidious polynomial" (1984); Snir (1986); Goldberg, "What every computer scientist should know about floating-point arithmetic" (1991); GAO IMTEC-92-26 (1992); Lions et al., Ariane 5 Flight 501 Failure (1996); Edelman, "The mathematics of the Pentium division bug" (1997); Gustafson & Yonemoto (2017); Micikevicius et al., "FP8 formats for deep learning" (2022); IEEE 754 (1985, 2008, 2019); Volder (1959).
Technical scope checked on 9 November 2026: the FAA's 2015 directive
reports a 248-day internal GCU counter overflow but does not specify its width or units; the centisecond example is illustrative.
The conditional circuit bound is stated in the ICALP 2019 paper.
Current function coverage and integration claims come from CORE-MATH and its
FAQ, not an independent proof audit.
Python's math.fsum documentation records the possible double-rounding exception.
About this partfrom its README
Part 4 of a sixty-one-part course in computer science (see the series plan and
the syllabus). A machine has only finitely many bits, so its integers live on a clock and its reals
on a sparse, uneven ruler. The carry chain that makes addition slow turns, seen the right way, into a parallel prefix
computation; multipliers become trees of adders; division hides a table that cost Intel $475 million; and floating
point is carefully engineered, yet a wrong number can still bring down a rocket. Every circuit here is a netlist in
explainer/cs/pebble/blocks.py, checked against Python's integers (exhaustively where the inputs are few) and timed
gate by gate with Circuit.settle (unit delays, which sees through false paths); every number is computed in
compute.py.
- Numbers that run out. YouTube's 32-bit view counter (2014), the Boeing 787's 248-day generator bug (2015),
0.1 + 0.2; integers on a clock and reals on an uneven ruler; objectives. - 1. Bits as numbers. Positional notation; Leibniz (1679); why two levels (noise, drawn); decimal to binary by halving; hexadecimal.
- 2. Integers on a clock. Arithmetic mod 2ⁿ on a 4-bit wheel; two's complement as a relabelling (von Neumann, 1945): one adder for signed and unsigned; negation = invert + 1, proved; sign extension; −(−128) = −128; overflow: unsigned is the carry out, signed is carry-in ≠ carry-out of the top bit; what C, Java, Go, Rust and Python do.
- 3. Adding, one bit at a time. Binary addition by hand; half and full adders (five gates); the ripple-carry adder and subtraction as a + b̄ + 1; correctness by induction on the bits; the carry rippling, simulated (2n + 1 gate delays; 129 at 64 bits).
- 4. Carries in parallel. Generate, propagate, kill; carry lookahead unrolled; a block as a function of its carry-in (kill, propagate, generate), so the carry operator (g, p) ∘ (g′, p′) = (g + pg′, pp′) is function composition and associative; the ripple chain, Kogge–Stone (1973), Brent–Kung (1982) and Sklansky (1960) drawn on 16 positions (15/49/26/32 combines, depth 15/4/7/4, fan-out 2/2/2/9); Snir's size + depth ≥ 2n − 2 (1986).
- 5. The adders, raced. Carry-select (O(√n)); carry-skip, whose deepest path (81 gates at 32 bits) is false and whose largest observed delay in these test vectors is 29; delay and gates for six designs from 4 to 64 bits; 64 bits: ripple 320 gates / 129 delays, Kogge–Stone 1,094 / 15.
- 6. Multiplication. Shift and add; the array multiplier (O(n)); carry-save addition as 3:2 compression; the Wallace tree (1964) compressing 8 → 6 → 4 → 3 → 2, and Dadda's (1965); Booth recoding (1951; radix 4, MacSorley 1961) of 118 as 2·4³ − 4² + 2·4 − 2; measured at 16 bits: array 88 delays, Wallace 28, Dadda 25.
- 7. Division, and a famous bug. Restoring division of 200 by 13, traced; non-restoring; radix-4 SRT (Sweeney, Robertson, Tocher, 1958) with redundant digits −2…2; our quotient-digit table (1,056 cells, each checked) drawn as a map; random divisions never visit 208 of its cells; the Pentium FDIV bug (Nicely, 1994: five of 1,066 entries missing, 4195835/3145727, about 1 in 9 billion divisions, $475 million) and a toy version: five emptied cells, 18,603 of 2,000,000 divisions wrong; Newton–Raphson reciprocals with quadratic convergence (derived), Goldschmidt.
- 8. Pebble's ALU. Adder/subtractor, logic, barrel shifter (left, right, arithmetic) and comparisons from one Kogge–Stone adder (sltu from the borrow, slt from the sign corrected by overflow); verified on all 655,360 cases at 8 bits and on 20,000 random and worst-case inputs at 32 bits against the emulator's semantics; 1,900 gates, measured delay 29 (78 with a ripple adder).
- 9. Fixed point. Q formats; money in integer cents; 0.1 = 0.0(0011)₂; dynamic range: Q16.16 covers 9 decades, float32 normal values span about 76 decades (subnormals extend the range with reduced precision).
- 10. Floating point. IEEE 754 (1985, Kahan): sign, biased exponent, hidden bit; 0.1 as stored; every value of a 6-bit float, bands doubling in spacing, subnormals; ulp and machine epsilon, the relative-spacing sawtooth; 2²⁴ + 1 is not a float32; ±0, ±∞, NaN, gradual underflow; correctly rounded operations, ties to even.
- 11. Rounding error. fl(x ∘ y) = (x ∘ y)(1 + δ); catastrophic cancellation in (1 − cos x)/x² and its stable rewrite; naive, pairwise and Kahan summation of a million float32 numbers, with their error bounds; the Patriot clock (1991: 0.34 s after 100 hours) and Ariane 5 (1996: a 64-bit float into a 16-bit integer).
- 12. Conditioning and stability. Condition number against backward stability, error ≲ κu; Wilkinson's polynomial with the x¹⁹ coefficient moved by 2⁻²³, roots animated from 60-digit computations (16.73 ± 2.81i, …); root sensitivity k¹⁹/∏|k − j| (2.4 × 10⁹ for root 16); what numerical software learned.
- 13. Beyond IEEE. binary64 to FP8, side by side; bfloat16 against binary16 and why machine learning chose range; FP8 (2022); interval arithmetic and the dependency problem; posits (2017); bignums.
- 14. Computing sin, exp and log. Range reduction (Payne–Hanek for huge arguments); a Remez minimax polynomial for eˣ against Taylor's (17× smaller error, equioscillating); CORDIC (Volder, 1959) rotating by arctan 2⁻ⁱ with shifts and adds, run for 16 steps; the HP-35.
- 15. Frontier: arithmetic's open questions. Multiplication measured on this machine: CPython's integers
(Karatsuba) against
decimal's number-theoretic transform, faster at a million digits (the measured ratio and slopes are on screen and vary by machine and run). The race to n log n: Karatsuba (1960), Toom–Cook, Schönhage–Strassen (1971), Fürer (2007), Harvey and van der Hoeven (2019). The galactic crossover 2^(1729¹²) is an illustrative asymptotic estimate, not a measured threshold. An unconditional linear lower bound is known; the network-coding conjecture implies Ω(n log n) size for constant-degree Boolean circuits (Afshani, Freksen, Kamma and Larsen, 2019), rather than an unconditional runtime bound. NumPy's float32expdisagrees with a float64-then-float32 reference on about 39% of 10 million sampled inputs on this machine (by 1 ulp, rarely 2); 200 disagreements are rechecked at 200 bits. This does not certify all reference values. The table-maker's dilemma; structured worst-case searches; CORE-MATH's existing binary32 and many binary64 routines, proofs for several binary64 functions, and the project's November 2026 report of seven binary64 functions integrated into glibc 2.43. Complete certified coverage, speed and adoption remain active work. - Recap, where this comes back, in practice, problems.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Positional notation; why binary (noise margins); hexadecimal.
- Integers mod 2ⁿ: overflow as wraparound on a clock. Two's complement as a relabeling of ℤ/2ⁿℤ, so one adder serves signed and unsigned. Negation = invert + 1 (proved). Sign extension.
- Half and full adders. The ripple-carry adder, correct by induction, with delay Θ(n) measured.
- Carry lookahead: generate and propagate. The carry operator (g, p) ∘ (g′, p′) is associative, which gives a parallel prefix tree. Kogge–Stone, Brent–Kung and Sklansky drawn: depth O(log n), with their size, depth and fan-out trade-offs. The prefix tree returns in Part 10 (scan).
- Carry-select and carry-skip adders (√n). Critical paths measured in our netlists.
- Multiplication: shift-and-add; the array multiplier; Booth recoding; carry-save 3:2 compressors; Wallace and Dadda trees, depth O(log n).
- Division: restoring and non-restoring. SRT, and the Pentium FDIV bug (1994): five missing table entries and a $475M charge. Newton–Raphson reciprocals with quadratic convergence (derived); Goldschmidt.
- Pebble's ALU assembled (add, sub, logic, shifts, compare): its gate count and critical path.
- Fixed point, and why its dynamic range isn't enough.
- IEEE 754 (1985, Kahan):
- sign, exponent, significand;
- the logarithmic spacing of floats (the camera zooms along the number line);
- ulp and machine ε;
- subnormals and gradual underflow; ±0, ∞, NaN;
- rounding modes and correctly rounded operations.
- Error analysis:
- the model fl(x ∘ y) = (x ∘ y)(1 + δ), |δ| ≤ u;
- catastrophic cancellation in (1 − cos x)/x²;
- Kahan's compensated summation, error bound proved against naive summation's nu, and pairwise summation;
- the Patriot clock (1991; 0.34 s after 100 hours) and Ariane 5 (1996; a 64-bit to 16-bit conversion).
- Conditioning against stability (Wilkinson): perturb one coefficient of ∏(x − k), k = 1…20, by 2⁻²³ and watch the roots fly into the complex plane (computed).
- Beyond IEEE: bfloat16 and FP8 (callback to AI, Built 17); posits; interval arithmetic; bignums (Karatsuba waits for Part 19).
- Computing sin, exp and log: range reduction, minimax polynomials, CORDIC shift-and-add rotations (the HP-35). Outro.
Computed: ripple against lookahead delay over n; Wallace against array depth; a deliberately broken SRT table; Kahan against naive summation; Wilkinson's roots; CORDIC iterations. Visuals: the 2ⁿ clock; a prefix tree of carries lighting level by level; the float number line with its spacing doubling at each power of two; the roots scattering. In practice: integer-overflow bugs and CVEs, money in fixed point (never in floats), numerical libraries, ML number formats, the FDIV recall as a lesson in testing. Reading: Harris & Harris ch. 5; Parhami, Computer Arithmetic; Koren, Computer Arithmetic Algorithms; Goldberg, "What Every Computer Scientist Should Know About Floating-Point Arithmetic" (1991); Higham, Accuracy and Stability of Numerical Algorithms ch. 1–4; Muller et al., Handbook of Floating-Point Arithmetic; Knuth, TAOCP 2 §4.1–4.3; Overton, Numerical Computing with IEEE Floating Point Arithmetic.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
补码。 用 8 位写出 −37,并证明映射 x ↦ x̄ + 1 只把 0 和 −128 映到自身。
解答
37 = 00100101;取反得 11011010;加一得 11011011。不动点满足 x ≡ −x (mod 2⁸),即 2x ≡ 0 (mod 256), x ≡ 0 (mod 128):x = 0 或 x = 128,后者按有符号读作 −128。所以 −128 没有正的搭档。
-
有符号溢出。 证明 n 位有符号加法溢出,当且仅当进入最高位的进位不等于从最高位出去的进位。
解答
设最高位为 a、b,进入最高位的进位为 c,出去的进位为 c′,最高位的和 s = a ⊕ b ⊕ c。溢出指两个操作数同号而结果 异号:a = b ≠ s。若 a = b = 0,则 c′ = 0 且 s = c,溢出 ⇔ c = 1 ⇔ c ≠ c′。若 a = b = 1,则 c′ = 1 且 s = c,溢出 ⇔ c = 0 ⇔ c ≠ c′。若 a ≠ b,不可能溢出,且 c′ = c(这一列传递进位)。所以溢出 ⇔ c ≠ c′,一个异或门就能检测。
-
Kogge–Stone 的规模。 证明 n = 2ᵏ 个位置上的 Kogge–Stone 网络有 nk − n + 1 个合并。
解答
在第 l 层(跨度 d = 2ˡ),每个 i ≥ d 的位置都合并一次,共 n − 2ˡ 个。对 l = 0 … k − 1 求和: nk − (2ᵏ − 1) = nk − n + 1。n = 16 时为 64 − 16 + 1 = 49,与第4章的图一致(深度 k = log₂ n)。
-
进位保留。 证明逐位地有 x + y + z = (x ⊕ y ⊕ z) + 2·maj(x, y, z)。
解答
每一列的三个位 xᵢ、yᵢ、zᵢ 之和在 0 到 3 之间,等于 sᵢ + 2cᵢ,其中 sᵢ 是奇偶(异或),cᵢ 是多数——这正是全加器的 真值表。把第 i 列乘以 2ⁱ 再对 i 求和:左边是 x + y + z,右边是奇偶组成的字加上两倍的多数组成的字。各列之间没有进位移动,所以 这一步对任何 n 都只需一个全加器的延迟。
-
浮点数。 [1, 2) 中有多少个 float32 值?在 Python 的 binary64 算术中,为什么 0.5 + 0.25 = 0.75 是精确的,而 0.1 + 0.2 ≠ 0.3?
解答
在 [1, 2) 中指数固定,23 个小数位任取:共 2²³ = 8,388,608 个值(每个规格化的区间 [2ᵉ, 2ᵉ⁺¹) 都一样多)。 0.5、0.25 和 0.75 都是二进分数(分母是 2 的幂),可以精确表示,它们的精确和也可以,所以正确舍入原样返回。0.1、0.2 和 0.3 的二进制展开都是无限的;各自舍入后存储,舍入后的 0.1 加舍入后的 0.2,是一个与舍入后的 0.3 不同的双精度数 (0.30000000000000004 对 0.29999999999999998…)。这个不等式依赖格式:对应的 float32 加法结果与 float32 的 0.3 相等。
-
动手:进位选择加法器。 用
explainer/cs/pebble/blocks.py搭一个 8 位进位选择加法器,块大小为 2、3、3 位;在所有输入上 验证;并与行波加法器和 Kogge–Stone 比较。解答
carry_select_adder(8, [2, 3, 3]),用hdl.simulate在全部 2¹⁷ 个输入上模拟,处处等于 a + b + c。测得:94 个 门,12 个门延迟后稳定;行波加法器为 40 个门、17 个延迟,Kogge–Stone 为 70 个门、9 个延迟(默认块大小 1、2、3、2 为 105 个 门,也是 12 个延迟)。 -
★ 研究题:难舍入的单精度指数输入。 在 [−87.33, 88.72] 内筛查使 eˣ 接近舍入中点的 float32 输入, 再用高精度复核候选。要证明没有遗漏,还需要什么?
实验与局限。
compute_hardround用 NumPy float64exp筛查这个区间内的 2,237,667,740 个位模式, 端点先舍入到 float32,包括正负两个零,再用 mpmath 以 300 位精度复核 200 个候选。它不覆盖整个 float32 定义域,包括指数结果为非规格化数的区域。 这里没有建立 float64 筛查误差的严格界,所以候选表是实验结果,不是全域最难情形的证明。候选中最近的是 x = −14.56709003448486328125,eˣ 离中点只有 2.36 × 10⁻⁹ 个 float32 ulp。
24 − log₂(距离)约为 52.7 位,用于表示精度预算,不能当作最小精度的精确定理。其次为 −0.0073526(51.7) 和 1.5199 × 10⁻⁵(51.6)。第一个候选的中点距离约为 1.265 个 binary64 ulp;先把精确指数正确舍入到 binary64, 再舍入到 float32,会得到正确结果。因此,这个候选不能证明双精度不足。具体快速近似仍需严格的总误差界; 如果误差区间跨过中点,就必须提高精度或走后备路径。要把实验变成证书,需证明筛查误差和候选选取裕量,覆盖遗漏区域与特殊值,并用误差包围验证高精度舍入。 结构化搜索和格方法能排除大片范围,不必逐一计算每个输入。CORE-MATH 已提供许多正确舍入的 binary64 例程; 扩展有证明的覆盖范围、提升性能和推广采用,仍是活跃工作。
Build the film
python -m videos.cs.cs4.compute # the part's numbers, into .cache/cs4
python tools/build.py cs4 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs4 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs4. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs4.compute # every number in the part (about a minute)
python tools/build.py cs4 -q l # a 480p preview
python tools/build.py cs4 # 1080p